File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ public class AsyncAutoResetEvent
2+ {
3+ private readonly static Task completed = Task . FromResult ( true ) ;
4+ private readonly ConcurrentQueue < TaskCompletionSource < bool > > waiters = new ConcurrentQueue < TaskCompletionSource < bool > > ( ) ;
5+ private bool signaled ;
6+
7+ /// <summary>
8+ /// Initializes a new instance of the <see cref="AsyncAutoResetEvent"/>
9+ /// class with a Boolean value indicating whether to set the initial state to signaled.
10+ /// </summary>
11+ /// <param name="signaled">if set to <c>true</c> [signaled].</param>
12+ public AsyncAutoResetEvent ( bool signaled = false )
13+ {
14+ this . signaled = signaled ;
15+ }
16+
17+
18+ /// <summary>
19+ /// Switches state machine of the current task until the event is signaled,
20+ /// a signal.
21+ /// </summary>
22+ /// <returns></returns>
23+ public Task WaitAsync ( )
24+ {
25+ lock ( waiters )
26+ {
27+ if ( signaled )
28+ {
29+ signaled = false ;
30+ return completed ;
31+ }
32+ else
33+ {
34+ var tcs = new TaskCompletionSource < bool > ( ) ;
35+ waiters . Enqueue ( tcs ) ;
36+ return tcs . Task ;
37+ }
38+ }
39+ }
40+
41+ /// <summary>
42+ /// Sets the state of the event to signaled, allowing one or more waiting tasks to proceed.
43+ /// </summary>
44+ public void Set ( )
45+ {
46+ TaskCompletionSource < bool > toRelease = null ;
47+ lock ( waiters )
48+ {
49+ if ( waiters . Count > 0 )
50+ {
51+ waiters . TryDequeue ( out toRelease ) ;
52+ }
53+
54+ else if ( ! signaled )
55+ signaled = true ;
56+
57+ if ( toRelease != null )
58+ toRelease . SetResult ( true ) ;
59+ }
60+
61+ }
62+ }
You can’t perform that action at this time.
0 commit comments