Created
February 28, 2014 16:31
-
-
Save JeffreyZhao/9274183 to your computer and use it in GitHub Desktop.
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
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