Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Created February 28, 2014 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffreyZhao/9274183 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/9274183 to your computer and use it in GitHub Desktop.
public class AsyncCompletion
{
private static readonly TaskCompletionSource<Unit> CompletedSource;
static AsyncCompletion()
{
CompletedSource = new TaskCompletionSource<Unit>();
CompletedSource.SetResult(Unit.Default);
}
private readonly object _gate = new object();
private volatile TaskCompletionSource<Unit> _cts;
public Task Completion
{
get
{
if (_cts != null)
return _cts.Task;
lock (_gate)
{
if (_cts != null)
return _cts.Task;
_cts = new TaskCompletionSource<Unit>();
}
return _cts.Task;
}
}
public void Complete()
{
if (_cts == CompletedSource)
return;
TaskCompletionSource<Unit> cts;
lock (_gate)
{
if (_cts == CompletedSource)
return;
cts = _cts;
_cts = CompletedSource;
}
if (cts != null)
{
cts.SetResult(Unit.Default);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment