开发者

Throwing an exception from a BackgroundWorker which calls an async. method (Webrequest)

  • My main application creates a new BackgroundWorker X
  • the DoWork event handler of X calls a method Y of my controller. This method creates the WebRequest (async.) instance and the callback using AsyncCallback.
  • When the response arrives the callback method Z gets called and the content will be analyzed. It can happen that the response has an unwanted content. At that moment callback Z will throw an exception.

I want to catch this exception in my main application. I tried it开发者_如何学JAVA in DoWork and RunWorkerCompleted but nothing can be caught from there.

Error in RunWorkerCompletedEventArgs is always null.


Dont know what you are doing wrong. But this works like 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 getting caught, and thus is prevented from propagating to the BWWorkCompletedEventArgs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜