简体   繁体   中英

Best practice to handle exception in the async call

For example, I am using wenclient.DownloadfileAsync to download a file asynchronously.

In the DownloadFileCompleted event handler, I can check if I have any exception or not by using AsyncCompletedEventArgs.Error property.

If I re-throw this exception, however my executable is stopping running immediately.

I am wondering how to handle this kind of exeception? How to pass this exception back to the calling thread?

The best way will be to use C# 5's async support :)

But you can pass the exception back to the calling thread in the same way that you pass the result. If you're using .NET 4, you could use Task<T> to allow the original thread to access the successful result or the exception. In fact, if they try to access the successful result and there was a failure, the exception will be thrown automatically (wrapped in an AggregateException ). The caller can check for the failure explicitly too.

If you're not using .NET 4, you can simulate all of this yourself, of course, by writing your own types with the appropriate properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM