| | | 1 | | namespace CounterpointCollective.Threading |
| | | 2 | | { |
| | | 3 | | /// <summary> |
| | | 4 | | /// Represents a lightweight, asynchronous manual reset event. |
| | | 5 | | /// </summary> |
| | | 6 | | /// <remarks> |
| | | 7 | | /// <para> |
| | | 8 | | /// This class provides a thread-safe, asynchronous alternative to <see cref="ManualResetEvent"/>. |
| | | 9 | | /// It allows waiting tasks to proceed when the event is set, until <see cref="Reset()"/> is called. |
| | | 10 | | /// </para> |
| | | 11 | | /// </remarks> |
| | | 12 | | public class AsyncManualResetEventSlim |
| | | 13 | | { |
| | 5 | 14 | | private volatile TaskCompletionSource<bool> tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Asynchronously waits for the event to be set. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <returns>A task that completes when the event is set.</returns> |
| | 9 | 20 | | public Task WaitAsync() => tcs.Task; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Sets the event, allowing all waiting tasks to complete. |
| | | 24 | | /// </summary> |
| | 8 | 25 | | public void Set() => tcs.TrySetResult(true); |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Resets the event to the non-signaled state. |
| | | 29 | | /// </summary> |
| | | 30 | | /// <remarks> |
| | | 31 | | /// After calling <see cref="Reset"/>, tasks that call <see cref="WaitAsync"/> will again |
| | | 32 | | /// wait until <see cref="Set"/> is called. |
| | | 33 | | /// </remarks> |
| | | 34 | | public void Reset() |
| | | 35 | | { |
| | 2 | 36 | | if (tcs.Task.IsCompleted) |
| | | 37 | | { |
| | 2 | 38 | | tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| | | 39 | | } |
| | 2 | 40 | | } |
| | | 41 | | } |
| | | 42 | | } |