When an async method that is awaited upon throws an exception, the exception is stored somewhere and throwing it is delayed. In a WinForms or WPF application, it uses SynchronizationContext.Current to post throwing of the exception. However, in e.g. a console application, it throws the exception on a thread pool and it brings down the application.
How can I prevent exceptions thrown from an async method from bringing down the application?
EDIT:
Appearantly the issue I’m describing is because I have void async methods. See comments.
When the
asyncmethod is started, it captures the current synchronization context. A way to solve this issue is to create your own synchronization context which captures the exception.The point here is that the synchronization context posts the callback to the thread pool, but with a try/catch around it:
In the
catchabove you can put your exception handling logic.Next, on every thread (
SynchronizationContext.Currentis[ThreadStatic]) where you want to executeasyncmethods with this mechanism, you must set the current synchronization context:The complete
Mainexample: