Is it OK to declare an async method as returning void to silence the CS4014 warning?

前端 未结 4 1917
南方客
南方客 2021-01-02 03:12

Visual Studio emits a warning for this code (\'because this call is not awaited, execution of the current method continues before the call is completed\').

s         


        
4条回答
  •  既然无缘
    2021-01-02 03:25

    It's extremely rare to have a true fire-and-forget operation; that is, an operation where:

    • No one cares when it completes.
    • No one cares if it completes.
    • No one cares if it throws an exception.

    Particularly with the last of these; most so-called "fire-and-forget" operations are not actually fire-and-forget because some action needs to be taken if it doesn't succeed.

    That said, there are a few situations where a true fire-and-forget is applicable.

    I prefer to use async Task and avoid the compiler warning by assigning the task to an otherwise unused variable:

    var _ = FireAndForget();
    

    async Task methods are more reusable and testable than async void methods.

    However, I wouldn't throw a fit if a developer on my team just used async void instead.

提交回复
热议问题