任务不等待完成 [英] Task is not waiting for completion
问题描述
我试图让自己等待和异步,所以我编写了这个小测试应用程序,但是我期望的结果没有实现.
I'm trying to get my head around await and async so I wrote this little test app, but what I expected does not happen.
程序不再等待任务完成,而是继续执行.
Instead of waiting for the task to complete, the program continues to execute.
class Program
{
static void Main(string[] args)
{
var task = new Task(Run);
task.Start();
task.Wait();
Console.WriteLine("Main finished");
Console.ReadLine();
}
public async static void Run()
{
var task = Task.Factory.StartNew(() =>
{
Console.WriteLine("Starting");
Thread.Sleep(1000);
Console.WriteLine("End");
});
await task;
Console.WriteLine("Run finished");
}
}
输出
Main finished
Starting
End
Run finished
如果我将等待任务"替换为"task.Await()",则它将按我预期的方式运行
If I swap the 'await task' for 'task.Await()' it then runs as I would have expected producing
Starting
End
Run finished
Main finished
推荐答案
这是因为当您具有异步 void
方法时,您无法采取任何措施来跟踪其完成情况.您的 new Task(Run)
仅创建用于启动Run方法的任务.在首次等待运行到达后,没有任何跟踪方法进度的信息,因为没有与方法进度相关的信息.要解决此问题,您必须返回 Task
而不是 void
并等待它,而不是创建新的Task.
That is because when you have asynchronous void
method, there is nothing you can do to track it's completion. Yours new Task(Run)
only creates a task for starting the Run method. After the Run arrives at first await, there is nothing tracking the progress of the method, because there is nothing associated with the progress of the method. To fix it, you have to return Task
instead of void
and await that, instead of creating new Task.
异步无效和异步任务
之间的差异"rel ="noreferrer">此处.
Difference between async void
and async Task
is described here.
这篇关于任务不等待完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!