RationalGeek
RationalGeek

Reputation: 9599

Await method that returns Task - spins forever?

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?

Upvotes: 1

Views: 1109

Answers (1)

SLaks
SLaks

Reputation: 887867

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.

Upvotes: 5

Related Questions