Last active
August 29, 2015 13:56
-
-
Save waynebaby/9276525 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 | |
{ | |
static AsyncCompletion() | |
{ | |
CompletedSource = new TaskCompletionSource<Unit>(); | |
CompletedSource.SetResult(Unit.Default); | |
} | |
int completed = 0; | |
bool completionFetched ; | |
/// <summary> | |
/// 静态完成源 | |
/// </summary> | |
static readonly TaskCompletionSource<Unit> CompletedSource; | |
/// <summary> | |
/// 跟着实例走的默认未完成源 | |
/// </summary> | |
Lazy<TaskCompletionSource<Unit>> _incompletByDefaultSource = | |
new Lazy<TaskCompletionSource<Unit>>(() => new TaskCompletionSource<Unit>(), true); | |
public Task Completion | |
{ | |
get | |
{ | |
completionFetched = true; | |
//如果完成了就只返回静态完成源,否则返回引用中的默认未完成源 | |
return (completed == 0) ? _incompletByDefaultSource.Value.Task : CompletedSource.Task; | |
} | |
} | |
public void Complete() | |
{ | |
//标记完成 | |
var isFirstComplete = Interlocked.Exchange(ref completed, 1) == 0; | |
//如果有人拿过默认未完成源 且当前是第一次完成 那么就把未完成源设置为完成] | |
if (completionFetched && isFirstComplete) | |
{ | |
var cts = _incompletByDefaultSource.Value; | |
cts.SetResult(Unit.Default); | |
} | |
} | |
} |
Author
waynebaby
commented
Feb 28, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment