强制任何任务附加到父级

Force any task to be attached to parent

我正在尝试创建一个扩展方法,将任何任务附加到父级。

分机号:[=​​12=]

internal static class TaskHelpers
{
    public static Task AttachToParrent(this Task task)
    {
        var tsc = new TaskCompletionSource<Task>(task.CreationOptions &    TaskCreationOptions.AttachedToParent);

        task.ContinueWith(_ => tsc.TrySetResult(task), TaskContinuationOptions.OnlyOnRanToCompletion);

        task.ContinueWith(t => tsc.TrySetException(task.Exception ?? new AggregateException(new ApplicationException("Unknown"))), TaskContinuationOptions.OnlyOnFaulted);

        task.ContinueWith(t => tsc.TrySetCanceled(), TaskContinuationOptions.OnlyOnCanceled);

        return tsc.Task.Unwrap();
    }
}

测试代码:

  static void Main(string[] args)
    {
        var  cancellationTokenSource = new CancellationTokenSource();

        var task1 = Task.Factory.StartNew(() =>
        {
            var task2 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 5; i++)
                {


                    if (!cancellationTokenSource.IsCancellationRequested)
                    {
                        Console.WriteLine(i);

                        Thread.Sleep(5000);
                    }
                    else
                    {
                        Console.WriteLine("Loop cancelled.");

                        break;
                    }
                }

            }, cancellationTokenSource.Token).AttachToParrent();

            var task3 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 5; i++)
                {

                    if (!cancellationTokenSource.IsCancellationRequested)
                    {
                        Console.WriteLine(i*10);

                        Thread.Sleep(5000);
                    }
                    else
                    {
                        Console.WriteLine("Loop cancelled.");

                        break;
                    }
                }

            }, cancellationTokenSource.Token).AttachToParrent();
        }, cancellationTokenSource.Token);

        Console.WriteLine("Enter to cancel");

        Console.ReadKey();

        cancellationTokenSource.Cancel();

        Console.WriteLine("Waiting To Be Cancelled");

        task1.Wait();

        Console.WriteLine("Task Cancelled");

        Console.ReadKey();
    }

父任务立即取消,不等待内部任务完成。我该如何解决它,作为输入,我正在执行我的父调度程序任务中的任务。我想执行附加到父级的任何任务。

调用Task.Factory.StartNew时只需提供TaskCreationOptions.AttachedToParent(仅在创建子任务时):

var task2 = Task.Factory.StartNew(..., cancellationTokenSource.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);

有关 Attached/Detached 任务的更多信息:请参阅 MSDN

发现问题出在

var tsc = new TaskCompletionSource<Task>(task.CreationOptions &    TaskCreationOptions.AttachedToParent); 

tsc,CreationOptions 保持为 nooptions。

改为

var tsc = new TaskCompletionSource<Task>(TaskCreationOptions.AttachedToParent); 

现在一切正常。