Best practice to handle exception in the async call
For example, I am using wenclient.DownloadfileAsync to download a file asy开发者_JAVA百科nchronously.
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.
精彩评论