我有任务、任务 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);
}
我应该选择哪种方式?它们是否同样有效?有没有更好的方法来编写这个?