File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- using System . Threading . Tasks ;
1+ using System . Threading ;
2+ using System . Threading . Tasks ;
23
34namespace dotnetCampus . Threading
45{
@@ -33,41 +34,38 @@ public AsyncManualResetEvent(bool initialState)
3334 /// <returns></returns>
3435 public Task WaitOneAsync ( )
3536 {
36- lock ( _locker )
37- {
38- return _source . Task ;
39- }
37+ return _source . Task ;
4038 }
4139
4240 /// <summary>
4341 /// 设置一个信号量,所有等待获得信号
4442 /// </summary>
4543 public void Set ( )
4644 {
47- lock ( _locker )
48- {
49- _source . SetResult ( true ) ;
50- }
45+ _source . TrySetResult ( true ) ;
5146 }
5247
5348 /// <summary>
5449 /// 设置一个信号量,所有wait等待
5550 /// </summary>
5651 public void Reset ( )
5752 {
58- lock ( _locker )
53+ while ( true )
5954 {
60- if ( ! _source . Task . IsCompleted )
55+ var tcs = _source ;
56+ if ( ! tcs . Task . IsCompleted )
6157 {
6258 return ;
6359 }
6460
65- _source = new TaskCompletionSource < bool > ( ) ;
61+ var newTcs = new TaskCompletionSource < bool > ( ) ;
62+ if ( Interlocked . CompareExchange ( ref _source , newTcs , tcs ) == tcs )
63+ {
64+ return ;
65+ }
6666 }
6767 }
6868
69- private readonly object _locker = new object ( ) ;
70-
71- private TaskCompletionSource < bool > _source ;
69+ private volatile TaskCompletionSource < bool > _source ;
7270 }
7371}
You can’t perform that action at this time.
0 commit comments