DotNext by Roman Sakno

<PackageReference Include="DotNext" Version="1.0.1" />

 Continuation

public static class Continuation
Represents various continuations.
using DotNext.Generic; using DotNext.Runtime; using System; using System.Threading; using System.Threading.Tasks; namespace DotNext.Threading.Tasks { public static class Continuation { private static Task<T> ContinueWithConstant<T, C>(Task<T> task, bool completedSynchronously, Func<Task<T>, T> continuation, CancellationToken token = default(CancellationToken), TaskScheduler scheduler = null) where C : Constant<T>, new { if (!completedSynchronously) return task.ContinueWith(continuation, token, TaskContinuationOptions.ExecuteSynchronously, scheduler ?? TaskScheduler.Current); return CompletedTask<T, C>.Task; } public static Task<Task> OnCompleted(this Task task) { return task.ContinueWith(Func.Identity<Task>(), Intrinsics.DefaultOf<CancellationToken>(), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current); } public static Task<Task<R>> OnCompleted<R>(this Task<R> task) { return task.ContinueWith(Func.Identity<Task<R>>(), Intrinsics.DefaultOf<CancellationToken>(), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current); } public static Task<T> OnFaulted<T, C>(this Task<T> task, TaskScheduler scheduler = null) where C : Constant<T>, new { return ContinueWithConstant<T, C>(task, task.IsFaulted, Continuation<T, C>.WhenFaulted, Intrinsics.DefaultOf<CancellationToken>(), scheduler); } public static Task<T> OnFaultedOrCanceled<T, C>(this Task<T> task, TaskScheduler scheduler = null) where C : Constant<T>, new { return ContinueWithConstant<T, C>(task, task.IsFaulted | task.IsCanceled, Continuation<T, C>.WhenFaultedOrCanceled, Intrinsics.DefaultOf<CancellationToken>(), scheduler); } public static Task<T> OnCanceled<T, C>(this Task<T> task, TaskScheduler scheduler = null) where C : Constant<T>, new { return ContinueWithConstant<T, C>(task, task.IsCanceled, Continuation<T, C>.WhenCanceled, Intrinsics.DefaultOf<CancellationToken>(), scheduler); } } }