简体   繁体   中英

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

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?

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

Probably to avoid spurious warnings on legacy code. Task predated async , and there's a number of methods out there that return Task but don't have anything to do with asynchronous code.

Personally, I think ignoring a Task return value is almost certainly a mistake, even in non-asynchronous code. But I assume that the MS team ran metrics and determined this warning would be too noisy for those kinds of code bases.

The warning isn't issued because no Task is dropped on the floor. The Task is being returned, so the caller is entirely capable of observing it. The warning exists to point out tasks that are not being observed. It would be wrong to produce a warning.

The code is correct; producing a warning for correct code is very problematic, as it's likely to result in the programmer changing it into incorrect code, worse code, confusion on there part as to what the problem is (because there isn't one) or, at the very least, them needing to spend extra work to work around a bad warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM