Esempio n. 1
0
 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);
     }
 }
Esempio n. 2
0
        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);
        }
Esempio n. 3
0
        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");
                    }
                }
        }
Esempio n. 4
0
 public bool TryCancel() => _inner.TryCancel();