Y型任务执行
本文关键字:执行 任务 | 更新日期: 2023-09-27 18:29:59
我有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);
}
我应该选择哪种方式?它们的效率都一样吗?有没有更好的方法来写这个?
我认为更好的方法是为后续的Task
s创建单独的async
方法
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)
来影响它。
这真的不是一个答案,只是另一个替代
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);
});
});