2

我有任务、任务 1 和任务 2。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);
}

我应该选择哪种方式?它们是否同样有效?有没有更好的方法来编写这个?

4

2 回答 2

2

我认为编写它的更好方法是async为后续Tasks 创建单独的方法。就像是:

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

于 2013-09-02T17:00:07.910 回答
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);
            });
    });
于 2013-09-02T21:59:13.880 回答