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

前端 未结 4 1934
南方客
南方客 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:16

    Is it OK to have a 'async void' method if the method is not designed to be awaitable in the first place and if no exception will be thrown?

    Although it may be "OK" to do so, I would still encourage you to make the method async Task. Even though you are a 100 percent sure this method won't throw, and isn't ment to be awaited, you never know how it might end up getting used. You're now fully aware of what the consequences of using async void are, but if there's a slight chance that someone might need to use this in the future, then you're better of putting a nice comment on why this Task isn't being awaited instead of going with the easy path of making this void.

    Don't let the compiler warnings worry you, I would say worry about the correctness and the effects this may have on your codebase.

提交回复
热议问题