I'm trying to get my head around this code:
[TestFixture]
public class ExampleTest
{
[Test]
public void Example()
{
AwaitEmptyTask().Wait();
}
public async Task AwaitEmptyTask()
{
await new Task(() => { });
}
}
The method Example
never ends and blocks forever. Why??
The fix (from Stubbing Task returning method in async unit test) is to replace await new Task( () => {})
with return Task.FromResult<object>(null);
but again, why is this necessary?
I know there are a bunch of questions similar to this one, but none that I've seen seem to explain why this is happening:
- Await method that returns Task - spins forever?: I included the
await
keyword AFAIK correctly - Stubbing Task returning method in async unit test: Doesn't explain why.
- Why will an empty .NET Task not complete if started and waited for from a static constructor?: I'm not running in a static context and as far as I can tell the context is consistent
- Async methods return null: also gives the solution, but doesn't explain why
- async await return Task: discusses
Task.FromResult
but not whyawait new Task(() => {})
doesn't work
Task.Factory.StartNew
to not forget to start a task – Alex ZhukovskiyTask.Factory.StartNew
and usesTask.Run
instead. There are issues with using StartNew. – Scott Chamberlain