Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

c# - Catch unhandled exceptions from async

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How can I prevent exceptions thrown from an async method from bringing down the application?

Follow these best practices:

  1. All async methods should return Task or Task<T> unless they have to return void (e.g., event handlers).
  2. At some point, you should await all Tasks 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).
  3. If you need to catch an exception from an 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...