async void
I have a 'void' return type method that needs to launch an async method.
1. I could use try-catch (I'm used to this approach usually, since the errors can be wrapped up)
2. Another suggested answer: Always successful Task (handle exception on the async Task pipeline directly)
Couldn't the Task method here just be made async anyway? (I mean i know it works without the async, but feels pointless unless deferred awaiting here improves performance in a way i can't see yet)
3.
ContinueWith
(this is my main confusion; Does this work? Is this better than #1?)
10 Replies
1
if i see an async void without a try catch thats a red flag for me
also id avoid 3 because of ContinueWith's footguns
I usually dont use ContinueWith because...it feels like unknown (or rather, potentially volatile) territory for me.. I get what it does(the logic in that code seems sound, on paper), but my code somehow feels safer without it.
Can you explain what you meant by 'footguns' in this case?
yeah i personally havent come across any reason to use ContinueWith in modern code
footguns means important things that are easy to get wrong
with ContinueWith for example there are a hundred flags where you need to specify the correct flag for the correct use case to get the behavior you want
so unless youre used to it and have a good understanding of how it works youre likely to get something wrong at some point
right
e.g. attatched/detached, errors getting swallowed when chaining them
yeah... I guess that lines up with why i avoid it.
Is this in an event handler?
Is async void really necessary?
In blazor for example it is perfectly happy to accept Task returning functions for EventCallback
it is, yeah.
pre .NET code
maybe even .netfx 1.1 or something
personally thought 2 try catch wouldn't catch anything because you imyediatly return the control flow. correct me if I'm wrong huuum
continueWith doesn't capture the SyncContext, it will continue on the threadpool thread, it can be pain if you for example working with UI which expect them be executed on the ui thread