Esempio n. 1
0
        /// <summary>
        /// Schedules the continuation onto the <see cref="Task"/> associated with this <see cref="TaskAwaiter"/>.
        /// </summary>
        /// <param name="task">The awaited task.</param>
        /// <param name="continuation">The action to invoke when the await operation completes.</param>
        /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="continuation"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="NullReferenceException">The awaiter was not properly initialized.</exception>
        /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
        internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext)
        {
            if (continuation == null)
            {
                throw new ArgumentNullException("continuation");
            }

            SynchronizationContext sc = continueOnCapturedContext ? SynchronizationContext.Current : null;

            if (sc != null && sc.GetType() != typeof(SynchronizationContext))
            {
                task.ContinueWith(param0 =>
                {
                    try
                    {
                        sc.Post(state => ((Action)state).Invoke(), continuation);
                    }
                    catch (Exception exception)
                    {
                        AsyncServices.ThrowAsync(exception, null);
                    }
                });//, CancellationToken.None);, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                return;
            }

            TaskScheduler taskScheduler = Task.DefaultScheduler;

            if (task.IsCompleted)
            {
                //Task.Factory.StartNew(s => ((Action)s).Invoke(), continuation, CancellationToken.None, TaskCreationOptions.None, taskScheduler);
                continuation();
                return;
            }

            //if (taskScheduler != TaskScheduler.Default)
            //{
            //    task.ContinueWith(_ => RunNoException(continuation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, taskScheduler);
            //    return;
            //}

            task.ContinueWith(param0 =>
            {
                if (IsValidLocationForInlining)
                {
                    RunNoException(continuation);
                    return;
                }

                //Task.Factory.StartNew(s => RunNoException((Action)s), continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                continuation();
            });//, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }