强制将任何任务附加到父任务

本文关键字:任务 任何 | 更新日期: 2023-09-27 18:20:01

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

扩展码:

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

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

发现问题,问题在中

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

tsc,CreationOptions保留为nooptions。

已更改为

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

现在一切正常。