如何等待直到Task.ContinueWith内部任务完成 [英] How to await until Task.ContinueWith inner task finishes
问题描述
看看下面的代码:
private async Task InnerTask(bool outerTaskResult)
{
Console.WriteLine("2");
await Task.Factory.StartNew(() => Thread.Sleep(10000));
Console.WriteLine("3");
}
private async void Button2_Click(object sender, RoutedEventArgs e)
{
var task = Task.FromResult(false);
Task<Task> aggregatedTask = task.ContinueWith(task1 => InnerTask(task1.Result));
Console.WriteLine("1");
await aggregatedTask;
Console.WriteLine("4");
}
所需的输出为:
1
2
3
4
但是我得到:
1
2
4
3
这可能与在不同线程上执行InnerTask有关。
This probably has something to do with InnerTask being executed on a different thread.
我使用ContinueWith是因为原始代码中的任务是通过这种方式动态创建和排队的。
I'm using ContinueWith because the tasks in the original code are dynamically created and queued this way.
使用 .Wait()方法(见下文)有效,但我认为这是一个坏主意,因为该方法正在阻塞。
Using .Wait() method (see below) works, but I think it's a bad idea, as the method is blocking.
task.ContinueWith(task1 => InnerTask(task1.Result).Wait())
这里的正确方法是什么?
What's the correct approach here?
推荐答案
您可以使用 TaskExtensions.Unwrap()
(这是 Task< Task>
的扩展方法)来展开外部任务并检索内部任务:
You can use TaskExtensions.Unwrap()
(which is an extension method on Task<Task>
) to unwrap the outter task and retrieve the inner one:
private async void Button2_Click(object sender, RoutedEventArgs e)
{
var task = Task.FromResult(false);
Task aggregatedTask = task.ContinueWith(task1 => InnerTask(task1.Result)).Unwrap();
Console.WriteLine("1");
await aggregatedTask;
Console.WriteLine("4");
}
请注意,为了简化整件事,而不是 ContinueWith
样式延续,您可以等待
完成任务:
Note that to simplify this entire thing, instead of ContinueWith
style continuation you can await
on your tasks:
private async void Button2_Click(object sender, RoutedEventArgs e)
{
var task = Task.FromResult(false);
Console.WriteLine("1");
var result = await task;
await InnerTask(result);
Console.WriteLine("4");
}
这篇关于如何等待直到Task.ContinueWith内部任务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!