Throwing an exception from BackgroundWorker, which makes an asynchronous call. method (Webrequest)
- My main application creates a new BackgroundWorker X
- DoWork X event handler calls method Y of my controller. This method creates a WebRequest (async.) Instance and a callback using AsyncCallback.
- When a response comes in, the Z callback method is returned and the content is parsed. It may happen that the response has inappropriate content. At this point, callback Z throws an exception.
I want to catch this exception in my main application. I tried it in DoWork and RunWorkerCompleted, but nothing to catch from there.
The error in the RunWorkerCompletedEventArgs is always zero.
+2
source to share
1 answer
Don't know what you are doing wrong. But it works like a charm.
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (o, s) => { throw new Exception("myMessage"); };
bw.RunWorkerCompleted += (o, s) => { Console.WriteLine(s.Error.Message); };
bw.RunWorkerAsync();
Console.ReadKey(true);
So this means that somewhere your exception must be caught and thus not allowed to propagate to BWWorkCompletedEventArgs
+2
source to share