Y风格的任务执行

时间:2013-09-02 16:33:33

标签: c# .net parallel-processing task-parallel-library async-await

我有Task,Task1和Task2。 Task1和Task2彼此独立,但都取决于Task的结果。我可以这样做:

static async Task Test1()
{
    var task = Task.Delay(1000);

    var task1 = task.ContinueWith(_ => 
    {
        Console.WriteLine("Task1, thread: {0}", Thread.CurrentThread.ManagedThreadId);
    });

    var task2 = task.ContinueWith(_ =>
    {
        Console.WriteLine("Task2, thread: {0}", Thread.CurrentThread.ManagedThreadId);
    });

    await Task.WhenAll(task1, task2);
}

或者,或者,这样:

static async Task Test2()
{
    var task = Task.Delay(1000);
    await task;

    var task1 = Task.Run(() =>
    {
        Console.WriteLine("Task1, thread: {0}", Thread.CurrentThread.ManagedThreadId);
    });

    var task2 = Task.Run(() =>
    {
        Console.WriteLine("Task2, thread: {0}", Thread.CurrentThread.ManagedThreadId);
    });

    await Task.WhenAll(task1, task2);
}

我更喜欢哪种方式?它们都同样有效吗?有没有更好的方法来组成这个?

2 个答案:

答案 0 :(得分:2)

我认为更好的方法是为后续async创建单独的Task方法。类似的东西:

private static async Task Task1(Task task)
{
    await task;
    Console.WriteLine("Task1, thread: {0}", Thread.CurrentThread.ManagedThreadId);
}

private static async Task Task2(Task task)
{
    await task;
    Console.WriteLine("Task2, thread: {0}", Thread.CurrentThread.ManagedThreadId);
}

private static async Task Test1()
{
    var task = Task.Delay(1000);

    var task1 = Task1(task);
    var task2 = Task2(task);

    await Task.WhenAll(task1, task2);
}

对于同步上下文(如果存在),这将与您的代码的行为不同,但您可以使用await task.ConfigureAwait(false)来影响它。

答案 1 :(得分:1)

这真的不是一个答案,只是另一种选择

var task = Task.Delay(1000);
await task.ContinueWith(_ =>
    {
        Parallel.Invoke(
            () => {
                Console.WriteLine("Task1, thread: {0}",Thread.CurrentThread.ManagedThreadId);
            },
            () => {
                Console.WriteLine("Task2, thread: {0}", Thread.CurrentThread.ManagedThreadId);
            });
    });