private static void PropagateCompletedTaskToPromise <T>(Task <T> task, Promise <T> promise) { if (task.IsCanceled) { promise.TryCancel(); } else if (task.IsFaulted) { promise.TryFail(task.Exception.InnerExceptions); } else { promise.TryComplete(task.Result); } }
public static Task <T> AsTask <T>(this CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(TaskConstants <T> .Canceled); } if (!cancellationToken.CanBeCanceled) { return(TaskConstants <T> .Infinite); } var promise = new Promise <T>(); var registration = cancellationToken.Register(() => promise.TryCancel()); var task = promise.Task; task.ContinueWithInBackground(t => registration.Dispose(), CancellationToken.None).IgnoreAwait(Log); return(task); }
public static async Task <T> WithTimeoutAsync <T>(this Task <T> task, TimeSpan timeout) { var timeoutPromise = new Promise(); using (var cancellation = new CancellationTokenSource(timeout)) using (cancellation.Token.Register(() => timeoutPromise.TryCancel())) { var completed = await Task.WhenAny(task, timeoutPromise.Task).ConfigureAwait(false); if (completed == task) { return(task.GetResult()); } else { throw new TimeoutException( $"Task did not completed in the specified timeout {timeout.TotalMilliseconds}ms"); } } }
public bool TryCancel() => _inner.TryCancel();