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?
new Task(...)returns an unstartedTask.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.