Await method that returns Task - spins forever?

て烟熏妆下的殇ゞ 提交于 2019-12-11 04:27:29

问题


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());
    }
}

The first test, AwaitAsyncMethod(), completes successfully immediately upon execution. The second test, AwaitTaskMethod(), never completes. But it does compile.

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?


回答1:


new Task(...) returns an unstarted Task.
Until you call Start(), that task will never finish, and anything waiting for it will never run.

Instead, you can call Task.Run(), which will create and start a task for you.



来源:https://stackoverflow.com/questions/13862829/await-method-that-returns-task-spins-forever

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!