Ejemplo n.º 1
0
        /// <summary>
        /// Queues a task for execution, and begins executing all tasks in the queue. This method returns when all tasks have been completed and the outstanding asynchronous operation count is zero. Returns the result of the task proxy. This method will unwrap and propagate errors from the task proxy.
        /// </summary>
        /// <typeparam name="TResult">The result type of the task.</typeparam>
        /// <param name="action">The action to execute. May not be <c>null</c>.</param>
        public static TResult Run <TResult>(Func <Task <TResult> > action)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            // ReSharper disable AccessToDisposedClosure
            using (var context = new AsyncContext())
            {
                context.OperationStarted();
                var task = context._taskFactory.Run(action).ContinueWith(t =>
                {
                    context.OperationCompleted();
                    return(t.WaitAndUnwrapException());
                }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, context._taskScheduler);
                context.Execute();
                return(task.WaitAndUnwrapException());
            }
            // ReSharper restore AccessToDisposedClosure
        }
 /// <summary>
 /// Responds to the notification that an operation has started by incrementing the outstanding asynchronous operation count.
 /// </summary>
 public override void OperationStarted()
 {
     _context.OperationStarted();
 }