Skip to content

Instantly share code, notes, and snippets.

@brsmith080
Created February 1, 2017 02:52
Show Gist options
  • Save brsmith080/9cf880fa64561b3b6bdc5550a99bc1d3 to your computer and use it in GitHub Desktop.
Save brsmith080/9cf880fa64561b3b6bdc5550a99bc1d3 to your computer and use it in GitHub Desktop.
continue to task
public static Task<TNewResult> ContinueWithTask<TContinue, TNewResult>(this Task<TContinue> task, Func<Task<TContinue>, Task<TNewResult>> Continuation, CancellationToken CancellationToken)
{
var Completion = new TaskCompletionSource<TNewResult>();
task.ContinueWith(t =>
{
if (CancellationToken.IsCancellationRequested)
{
Completion.SetCanceled();
return;
}
if (t.IsFaulted)
{
Completion.TrySetException(t.Exception);
return;
}
Continuation(t).ContinueWith(t2 =>
{
if (CancellationToken.IsCancellationRequested || t2.IsCanceled) Completion.TrySetCanceled();
else if (t2.IsFaulted) Completion.TrySetException(t2.Exception);
else Completion.SetResult(t2.Result);
});
});
return Completion.Task;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment