private static Task CopyResultToCompletionSourceImplContinuation <TTask, TResult>(TTask task, TaskCompletionSource <TResult> tcs, Func <TTask, TResult> resultThunk)
            where TTask : Task
        {
            return(task.ContinueWith(innerTask =>
            {
                switch (innerTask.Status)
                {
                case TaskStatus.Canceled:
                case TaskStatus.Faulted:
                    TaskHelpers.TrySetFromTask(tcs, innerTask);
                    break;

                case TaskStatus.RanToCompletion:
                    tcs.TrySetResult(resultThunk(task));
                    break;
                }
            }, TaskContinuationOptions.ExecuteSynchronously));
        }
        private static Task CopyResultToCompletionSourceImpl <TTask, TResult>(this TTask task, TaskCompletionSource <TResult> tcs, Func <TTask, TResult> resultThunk)
            where TTask : Task
        {
            // Stay on the same thread if we can
            if (task.IsCompleted)
            {
                switch (task.Status)
                {
                case TaskStatus.Canceled:
                case TaskStatus.Faulted:
                    TaskHelpers.TrySetFromTask(tcs, task);
                    break;

                case TaskStatus.RanToCompletion:
                    tcs.TrySetResult(resultThunk(task));
                    break;
                }

                return(TaskHelpers.Completed());
            }

            // Split into a continuation method so that we don't create a closure unnecessarily
            return(CopyResultToCompletionSourceImplContinuation(task, tcs, resultThunk));
        }