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.
How can I prevent exceptions thrown from an async method from bringing down the application?
Follow these best practices:
async
methods should return Task
or Task<T>
unless they have to return void
(e.g., event handlers).await
all Task
s returned from async
methods. The only reason you wouldn't want to do this is if you no longer care about the result of the operation (e.g., after you cancel it).async void
event handler, then catch it in the event handler - exactly like you would do if this was synchronous code.You may find my async
/ await
intro post helpful; I cover several other best practices there as well.