等待返回工作方法 - 不断旋转? [英] Await method that returns Task - spins forever?
问题描述
我有以下NUnit测试类:
I have the following NUnit test class:
[TestFixture]
public class Tests
{
async Task<string> GetMessageAsync()
{
return "Hello from GetMessageAsync!";
}
Task<string> GetMessageTask()
{
return new Task<string>(() => "Hello from GetMessageTask!");
}
[Test]
public async void AwaitAsyncMethod()
{
Assert.AreEqual("Hello from GetMessageAsync!", await GetMessageAsync());
}
[Test]
public async void AwaitTaskMethod()
{
Assert.AreEqual("Hello from GetMessageTask!", await GetMessageTask());
}
}
第一个测试,AwaitAsyncMethod(),在执行时成功完成,立即生效。第二次测试,AwaitTaskMethod(),永远不会完成。但它确实编译。
The first test, AwaitAsyncMethod(), completes successfully immediately upon execution. The second test, AwaitTaskMethod(), never completes. But it does compile.
为什么第二次测试永远不会完成?为什么我可以编译针对非异步方法的的await,如果看似不实际工作?比方说,由于某种原因,我想非异步方法返回,可以期待已久的一个任务 - 我怎么改变这个code来实现这一目标。
Why does the second test never complete? Why can I compile an await against a non-async method, if seemingly it doesn't actually work? Let's say for some reason I want a non-async method to return a task that can be awaited - how do I change this code to accomplish that?
推荐答案
新建任务(...)
返回一个尚未启动工作
。结果
直到调用开始()
,该任务将永远不会结束,而且什么都等着它永远不会运行。
new Task(...)
returns an unstarted Task
.
Until you call Start()
, that task will never finish, and anything waiting for it will never run.
相反,你可以叫 Task.Run()
,这将创建和启动一个任务给你。
Instead, you can call Task.Run()
, which will create and start a task for you.
这篇关于等待返回工作方法 - 不断旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!