Skip to content

Commit a8c4116

Browse files
authored
Merge pull request #77 from ZjzMisaka/master
Add CAS to AsyncManualResetEvent
2 parents f589e51 + 08138ac commit a8c4116

1 file changed

Lines changed: 13 additions & 15 deletions

File tree

AsyncWorkerCollection/AsyncManualResetEvent.cs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System.Threading.Tasks;
1+
using System.Threading;
2+
using System.Threading.Tasks;
23

34
namespace 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
}

0 commit comments

Comments
 (0)