Last active
August 29, 2015 13:56
-
-
Save waynebaby/9284249 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 | |
{ | |
/// <summary> | |
/// 跟着实例走的默认未完成源 | |
/// </summary> | |
Lazy<TaskCompletionSource<Unit>> _lazyIncompletByDefaultSource = | |
new Lazy<TaskCompletionSource<Unit>>(() => new TaskCompletionSource<Unit>(), true); | |
/// <summary> | |
/// 静态完成源 | |
/// </summary> | |
static Lazy<TaskCompletionSource<Unit>> CompletedSource = | |
new Lazy<TaskCompletionSource<Unit>>(() => | |
{ | |
var completedSource = new TaskCompletionSource<Unit>(); | |
completedSource.SetResult(Unit.Default); | |
return completedSource; | |
}, true); | |
public Task Completion | |
{ | |
get | |
{ | |
return _lazyIncompletByDefaultSource.Value.Task; | |
} | |
} | |
public void Complete() | |
{ | |
//标记完成 | |
// var oldOne = Interlocked.Exchange(ref _lazyIncompletByDefaultSource, CompletedSource); 可以加锁的替换 | |
var oldOne = _lazyIncompletByDefaultSource; | |
_lazyIncompletByDefaultSource = CompletedSource; | |
if (oldOne != CompletedSource) | |
{ | |
var cts = _lazyIncompletByDefaultSource.Value; | |
cts.TrySetResult(Unit.Default); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment