| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Threading.Tasks; |
| | 6 | |
|
| | 7 | | namespace Azure.Core.TestFramework |
| | 8 | | { |
| | 9 | | public class AsyncGate<TIn, TOut> |
| | 10 | | { |
| 15281 | 11 | | private readonly object _sync = new object(); |
| 15281 | 12 | | private TaskCompletionSource<TIn> _signalTaskCompletionSource = new TaskCompletionSource<TIn>(TaskCreationOption |
| 15281 | 13 | | private TaskCompletionSource<TOut> _releaseTaskCompletionSource = new TaskCompletionSource<TOut>(TaskCreationOpt |
| | 14 | |
|
| | 15 | | public async Task<TIn> WaitForSignal() |
| | 16 | | { |
| 602 | 17 | | return await _signalTaskCompletionSource.Task.TimeoutAfterDefault(); |
| 602 | 18 | | } |
| | 19 | |
|
| | 20 | | public async Task<TIn> Cycle(TOut value = default) |
| | 21 | | { |
| 538 | 22 | | TIn signal = await WaitForSignal(); |
| 538 | 23 | | Release(value); |
| 538 | 24 | | return signal; |
| 538 | 25 | | } |
| | 26 | |
|
| | 27 | | public async Task<TIn> CycleWithException(Exception exception) |
| | 28 | | { |
| 64 | 29 | | TIn signal = await WaitForSignal(); |
| 64 | 30 | | ReleaseWithException(exception); |
| 64 | 31 | | return signal; |
| 64 | 32 | | } |
| | 33 | |
|
| | 34 | | public void Release(TOut value = default) |
| | 35 | | { |
| 538 | 36 | | lock (_sync) |
| | 37 | | { |
| 538 | 38 | | Reset().SetResult(value); |
| 538 | 39 | | } |
| 538 | 40 | | } |
| | 41 | |
|
| | 42 | | public void ReleaseWithException(Exception exception) |
| | 43 | | { |
| 64 | 44 | | lock (_sync) |
| | 45 | | { |
| 64 | 46 | | Reset().SetException(exception); |
| 64 | 47 | | } |
| 64 | 48 | | } |
| | 49 | |
|
| | 50 | | private TaskCompletionSource<TOut> Reset() |
| | 51 | | { |
| 602 | 52 | | lock (_sync) |
| | 53 | | { |
| 602 | 54 | | if (!_signalTaskCompletionSource.Task.IsCompleted) |
| | 55 | | { |
| 0 | 56 | | throw new InvalidOperationException("No await call to release"); |
| | 57 | | } |
| | 58 | |
|
| 602 | 59 | | TaskCompletionSource<TOut> releaseTaskCompletionSource = _releaseTaskCompletionSource; |
| 602 | 60 | | _releaseTaskCompletionSource = new TaskCompletionSource<TOut>(TaskCreationOptions.RunContinuationsAsynch |
| 602 | 61 | | _signalTaskCompletionSource = new TaskCompletionSource<TIn>(TaskCreationOptions.RunContinuationsAsynchro |
| 602 | 62 | | return releaseTaskCompletionSource; |
| | 63 | | } |
| 602 | 64 | | } |
| | 65 | |
|
| | 66 | | public Task<TOut> WaitForRelease(TIn value = default) |
| | 67 | | { |
| 602 | 68 | | lock (_sync) |
| | 69 | | { |
| 602 | 70 | | _signalTaskCompletionSource.SetResult(value); |
| 602 | 71 | | return _releaseTaskCompletionSource.Task.TimeoutAfterDefault(); |
| | 72 | | } |
| 602 | 73 | | } |
| | 74 | | } |
| | 75 | | } |