Skip to content

Commit 5f5e3ed

Browse files
Create AsyncManualResetEvent.cs
1 parent 873eeac commit 5f5e3ed

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

AsyncManualResetEvent.cs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class AsyncManualResetEvent
2+
{
3+
private volatile TaskCompletionSource<bool> completionSource = new TaskCompletionSource<bool>();
4+
5+
/// <summary>
6+
/// Initializes a new instance of the <see cref="AsyncManualResetEvent"/> class with
7+
/// a Boolean value indicating whether to set the initial state to signaled.
8+
/// </summary>
9+
/// <param name="signaled">if set to <c>true</c> [signaled].</param>
10+
public AsyncManualResetEvent( bool signaled )
11+
{
12+
if (signaled)
13+
completionSource.TrySetResult(true);
14+
}
15+
16+
/// <summary>
17+
/// Waits the asynchronous.
18+
/// </summary>
19+
/// <returns></returns>
20+
public Task WaitAsync() { return completionSource.Task; }
21+
22+
/// <summary>
23+
/// Sets the state of the event to signaled, allowing one or more waiting tasks to proceed.
24+
/// </summary>
25+
public void Set() { completionSource.TrySetResult(true); }
26+
27+
/// <summary>
28+
/// Sets the state of the event to non signaled, allowing one or more waiting tasks to await.
29+
/// </summary>
30+
public void Reset()
31+
{
32+
while (true)
33+
{
34+
var tcs = completionSource;
35+
if (!tcs.Task.IsCompleted ||
36+
Interlocked.CompareExchange(ref completionSource, new TaskCompletionSource<bool>(), tcs) == tcs)
37+
return;
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)