Created
October 5, 2018 06:08
-
-
Save iyevhen/caaa9f03f7cb5394e51778003dfc5f7f to your computer and use it in GitHub Desktop.
Async with ManualResetEventSlim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://blogs.msdn.microsoft.com/calvin_hsia/2018/09/29/using-async-with-manualreseteventslim/ | |
// https://blogs.msdn.microsoft.com/pfxteam/2012/02/11/building-async-coordination-primitives-part-1-asyncmanualresetevent/ | |
internal class AsyncManualResetEvent | |
{ | |
private volatile TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); | |
public Task WaitAsync() => this.tcs.Task; | |
public void Set() | |
{ | |
// https://stackoverflow.com/questions/12693046/configuring-the-continuation-behaviour-of-a-taskcompletionsources-task | |
Task.Run(() => | |
this.tcs.TrySetResult(true)); | |
} | |
public void Reset() | |
{ | |
while (true) | |
{ | |
var tcs = this.tcs; | |
if (!tcs.Task.IsCompleted || | |
Interlocked.CompareExchange(ref this.tcs, new TaskCompletionSource<bool>(), tcs) == tcs) | |
{ | |
return; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment