Skip to content

Instantly share code, notes, and snippets.

@waynebaby
Last active August 29, 2015 13:56
Show Gist options
  • Save waynebaby/9284249 to your computer and use it in GitHub Desktop.
Save waynebaby/9284249 to your computer and use it in GitHub Desktop.
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