3 ms·
To be a bit facetious: remember that an unhandled exception in your main program thread will also crash your program. The article holds a very valuable lesson,
by zamalek 11y ago
To be a bit facetious: remember that an unhandled exception in your main program thread will also crash your program.
The article holds a very valuable lesson, though: just because you don't see "Task" doesn't mean that there aren't threads involved. In this way `async void` is deceptive but is certainly not something that is broken or something that you should never use. There is actually a case where an exception in one of these methods will not bring your process down:
async void button1_Click(object sender, EventArgs e) {
await Task.Delay(1000);
throw new Exception("No crash here!");
}
Why? A lesser known artifact from the .Net 2.0 days. In an unbelievable feat of foresight Microsoft wrote a class called SynchronizationContext[1]. It's a TLS object that defines a way to invoke methods on a well-known target. In the case of the one provided by System.Windows.Forms (which is active in the UI thread) it will dispatch callbacks back onto the main thread. Essentially what is happening with my above code is:
void button1_Click(object sender, EventArgs e) {
var sc = SynchronizationContext.Current;
Task.Delay(1000).GetAwaiter().OnCompleted(() => sc.Send(_ => {
// Back on the UI thread, thanks SynchronizationContext!
throw new Exception("No crash here!");
}, null));
}
The WindowsSynchronizationContext object (which is what SynchronizationContext.Current will point to on a UI thread) simply has a reference to the dispatcher and calls something similar to Control.Invoke(). This means that the code is re-routed back to the UI thread and because it occurs there you get the standard Windows.Forms error dialog with the option to "Quit" or "Continue" - ultimately preventing a crash. TPL leverages SynchronizationContext which is why this all works. Indeed, the very final example in the article (it looks like Windows.Timer) won't crash with `async void`.
As far as I remember, ASP.Net provides a SynchronizationContext for requests but I am unsure as to how it deals with exceptions (if it does at all). It's implementation specific.
Finally SynchronizationContext can be implemented by you allowing you to also deal with these exceptions in a clean/proper way[2]. Please don't ever do anything along the lines of `SwallowException`. Keep in mind that not everything takes advantage of SynchronizationContext (e.g. Threading.Timer) so it's definitely not a catch-all.
[1]: https://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx https://msdn.microsoft.com/en-us/library/system.threading.sy...
[2]: https://gist.github.com/jcdickinson/6aa4a09b60bd2469baf5 https://gist.github.com/jcdickinson/6aa4a09b60bd2469baf5
- mhomde 11y agoOn a related note, I really dislike the dispatcher paradigm, especially with the inclusion of async-await. For good performance of IO async calls you usually want to call .ConfigureWait(false), otherwise it will wait for the UI context to switch back to, you might even risk thread starvation. But now each async call is a potential switch out of the UI thread and certain crasch down the road, meaning you have to put Dispatcher.HasThreadAccess checks on all your UI methods. It just feels... clunky and unnecessarily explicit. In my opinion UI controls should be able to handle switching to UI context themselves and not crash the whole program, or if nothing else you should be able to annotate methods as UI threads rather than the clunky HasThreadAccess syntax. There's also these annoying "barriers" that you can't do certain UI stuff on background threads without some ugly hacks, like creating and working with images. The Dispatcher is cool for being able to prioritize UI operations though
- zamalek 11y ago> the dispatcher paradigm is one of the thing I dislike the most about coding UI stuff in .Net It inherits it from Windows. As far as I know, most GUIs have a dispatcher because <technical reasons>. I definitely think that there could have been a better way to solve the problem (method interception), however, I think that TPL does add value. In your case you cited intense IO as one reason to call `.ConfigureAwait(false).` The thing is: you have made a conscious decision to not return to the UI thread and therefore are more likely to tread carefully when writing the remainder of the method. `.ConfigureAwait(false)` declares "dragons be here." Previously someone who didn't know better would update the UI from the wrong thread, weird things happen and they don't know why. Here's something to make things simpler for you: https://gist.github.com/jcdickinson/f875229e671710cf1b34 https://gist.github.com/jcdickinson/f875229e671710cf1b34
- asveikau 11y ago> It inherits it from Windows. As far as I know, most GUIs have a dispatcher because <technical reasons>. This is a kind of lame elision. The classical Windows UI threading model is that every window has an owning thread [the thread it was created on], and that owning thread is supposed to drain its message queue periodically. You can send messages to another thread's object [either in blocking, via SendMessage, or enqueue without blocking for result, via PostMessage].