Why is CS4014 not shown for all functions that return a task?

Viewed 638

Suppose the following code:

private async Task Test1Async() => await Task.Delay(1000).ConfigureAwait(false);
private Task Test2Async() => Test1Async();

Functionally, these functions are exactly the same but the compiler treats calling these methods different. The following code compiles, but issues a CS4014 warning:

private void Test() => Test1Async();   // CS4014 is shown

It generates the warning "because this call is not awaited, the current method continues to run before the call is completed". This is a proper warning, because it often indicates a flaw in your code. In case you actually want this behavior, then you can solve it by using the following code:

private void Test() => _ = Test1Async();   // CS4014 is not shown anymore

Assigning the value to _ is a relative new feature to indicate that the value is ignored intentionally.

This code doesn't raise CS4014:

private void Test() => Test2Async();   // CS4014 is not shown!

Of course, I could rewrite all my methods to use the async/await method, but this results in more code that runs less efficient (due to the state machine generated by the async keyword). Maybe I will never forget about it, but my coworkers might and then I won't get a trigger (or I call a third-party library that doesn't use async).

There is also a difference in the warning about the returned Task usage.

Does anyone know why this warning is not generated for methods that return a Task that don't use the async keyword?

2 Answers
Related