Search code examples
c#asynchronousasync-awaitdesign-guidelines

why guidelines says "avoid async void" rather than saying "don't avoid awaiting on task"


Why guidelines says "avoid async void". I don't know, but I feel guideline should rather say - "await task". Problem with async void is that caller will not know if it need to await for completion and control will continue with execution of following statements. I can understand ill effect of this. But even if async method returns task instead of void, caller can still miss to await and get into same issues, right ? Hence the question, why not guideline rather says - don't avoid awaiting task


Solution

  • You can do that, i.e., you can do void or do not wait for task to complete at all.

    But there mayt be a scenario where you developed an API which is used by multiple projects, and some of the project which use your method want to wait to complete call although the method is going to returning nothing just for check or for doing work after method get completed.

    In that senario its helpful and that is the reason you must return Task not void. It helps the others who are using your method.

    That is one of the logic reason apart form what you have given in question.