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
keyword AFAIK correctlyTask.FromResult
but not why await new Task(() => {})
doesn't workThe await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
The Task<TResult> return type is used for an async method that contains a return statement in which the operand is TResult . In the following example, the GetLeisureHoursAsync method contains a return statement that returns an integer. The method declaration must specify a return type of Task<int> .
If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.
No, async await is just made to allow code to run whilst something else is blocking, and it doesn't do Task.
You're creating a task and never starting it, so it never finishes.
You should be using Task.Run
to create a task that you want to start executing immediately, rather than using the Task
constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With