强制将任何任务附加到父

时间:2015-11-01 14:13:24

标签: c# task-parallel-library task unwrap taskcompletionsource

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

分机代码:

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();
    }

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

2 个答案:

答案 0 :(得分:2)

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

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

有关附加/分离任务的更多信息:请参阅MSDN

答案 1 :(得分:1)

发现问题所在的问题

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

tsc,CreationOptions仍为nooptions。

已更改为

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

现在一切正常。