TPL中任务的排序

本文关键字:排序 任务 TPL | 更新日期: 2023-09-27 17:54:01

如果我有以下代码

using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
    class Program
    {
        static Task<int> GetSuperLargeNumber()
        {
            var main = Task.Factory.StartNew(() =>
                                                 {
                                                     Thread.Sleep(1000);
                                                     return 100;
                                                 });
            var second = main.ContinueWith(x => Console.WriteLine("Second: " + x.Result), TaskContinuationOptions.AttachedToParent);
            var third = main.ContinueWith(x => Console.WriteLine("Third: " + x.Result), TaskContinuationOptions.AttachedToParent);
            return main.ContinueWith(x  =>
                                             {
                                                 Task.WaitAll(second, third);
                                                 return x.Result;
                                             });
        }
        static void Main(string[] args)
        {
            GetSuperLargeNumber().ContinueWith(x => Console.WriteLine("Complete"));
            Console.ReadKey();
        }
    }
}

我希望main首先启动,然后可以启动两个依赖项,它们是第一个和第二个。然后,我想返回一个带有值的future,以便调用方在上面添加一个continuation。但是,我想确保第二个和第三个已经先运行。下面的代码是实现这一目标的最佳方式吗?看起来有点笨重的

TPL中任务的排序

我对TPL不太熟悉,但这不是ContinueWhenAll的用途吗?

static Task<int> GetSuperLargeNumber()
{
    var main = Task.Factory.StartNew(() =>
                                         {
                                             Thread.Sleep(1000);
                                             return 100;
                                         });
    var second = main.ContinueWith(
        x => Console.WriteLine("Second: " + x.Result),
        TaskContinuationOptions.AttachedToParent);
    var third = main.ContinueWith(
        x => Console.WriteLine("Third: " + x.Result),
        TaskContinuationOptions.AttachedToParent);
    return Task.Factory.ContinueWhenAll(
        new[] { second, third },
        (twotasks) => /* not sure how to get the original result here */);
    }

我不知道如何从完成的secondthird(包含在twotasks中(中获得main的结果,但也许你可以修改它们来传递结果。

编辑:或者,正如亚历克斯所指出的,使用

Task.Factory.ContinueWhenAll(new[] { main, second, third }, (threetasks) => ...

并从CCD_ 6中读取结果。

这就足够了:

static Task<int> GetSuperLargeNumber()
{
    var main = Task.Factory.StartNew<int>(() =>
    {
        Thread.Sleep(1000);
        return 100;
    });
    var second = main.ContinueWith(x => Console.WriteLine("Second: " + x.Result), TaskContinuationOptions.AttachedToParent);
    var third = main.ContinueWith(x => Console.WriteLine("Third: " + x.Result), TaskContinuationOptions.AttachedToParent);
    Task.WaitAll(second, third);
    return main;
}