UnhandledException not called when exception thrown in another thread

帅比萌擦擦* 提交于 2019-11-30 19:55:17

In your code UnhandledException isn't fired on any AppDomain, because if you call a delegate using BeginInvoke(), any exception that is thrown during its execution is handled and then rethrown when you call EndInvoke(), which you don't.

If you either call EndInvoke():

start.EndInvoke(start.BeginInvoke(null, null));

or execute the delegate synchronously:

start();

You get similar results: UnhandledException of the main domain is raised.

If instead, you do what the documentation says and start a new thread using the Thread class:

new Thread(Nested1ThreadStart).Start();

UnhandledException of Nested1 and the main app domain are raised.

So, to answer your question: The documentation is right. Your code is wrong. When you call delegate asynchronously using BeginInvoke(), you should always call EndInvoke() later.

I had this problem too. I used Observer Pattern to solve that. you can implement an interface in your caller class that have a method which call from the other thread when an exception occurs.

Here's a link that shows how to implement this pattern Exploring the Observer Design Pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!