Skip to content

Instantly share code, notes, and snippets.

@iyevhen
Created October 5, 2018 06:08
Show Gist options
  • Save iyevhen/caaa9f03f7cb5394e51778003dfc5f7f to your computer and use it in GitHub Desktop.
Save iyevhen/caaa9f03f7cb5394e51778003dfc5f7f to your computer and use it in GitHub Desktop.
Async with ManualResetEventSlim
// 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