Reputation: 4164
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
Upvotes: 0
Views: 140
Reputation: 176956
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.
Upvotes: -2
Reputation: 203825
You don't always want to prevent the rest of the method from executing until that operation has finished. Sometimes you have some things you can do before it finishes, so you want to await it later, maybe that one caller happens to just not need the results, so it can ignore it safely, etc. The point is, because the method returns a Task
it is up to the caller to do with it what they will. If they want to do something when that task finishes, or know if it has succeeded or failed, they can, and if they don't that's fine to.
When the method is an async void
method that is taken out of your hands. The caller is put into a position where they can't know when the operation has finished, even if they really need to know. And that's just not a decision that should be made when writing the method. That method isn't going to know who all is going to call it, and whether or not they'll need to know when/if it has finished, so when writing the method you need to assume that someone will want that information.
All of that said firing off an async method and ignoring it entirely should be very rare. There are situations where it's appropriate, but it should be a big red flag anytime you see it. When it does happen though, it should be the caller of the method making the decision that they don't care about when that operation finishes, not the author of the method deciding that no one should ever be able to know when it finishes (again, outside of some really exceptional situations).
Upvotes: 2