using System; using System.Threading.Tasks; namespace Sony.Filtr.ScheduledTask { public static class TaskExtensions { public static Task Select(this Task task, Func selector) { return task.ContinueWith(t => selector(t.Result)); } public static Task Bind(this Task task, Func> binder) { var tcs = new TaskCompletionSource(); task.ContinueWith(t => { if (t.IsFaulted) tcs.SetException(t.Exception); else if (t.IsCanceled) tcs.SetCanceled(); else { try { binder(t.Result).ContinueWith(b => tcs.SetResult(b.Result)); } catch (Exception ex) { tcs.SetException(ex); } } }); return tcs.Task; } public static Task OnSuccess(this Task task, Action action) { task.ContinueWith(t => action(t.Result), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion); return task; } public static Task OnFail(this Task task, Action action) { task.ContinueWith(t => action(t.Exception), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted); return task; } } }