开发者

exception handling in the multi thread environment

I want to know if

try/catch can catch the exceptions thrown by the children threads.

if not, what's the best practice to handling exceptions开发者_JAVA百科 thrown in the child thread.


You can listen to the Application.ThreadException and AppDomain.UnhandledException events to catch uncaught exceptions from thread. But the best is to catch and handle exceptions in the threads themselves. This should be a last resort for graceful shutdown / logging.


It depends on the .NET framework you're targeting.

In 1.1 and lesser, exceptions thrown by children threads will be forwarded to the main thread only if they run outside a try/catch block.

In 2.0 and later, this behaviour is changed: thread will be terminated and exceptions won't be allowed to proceed any further.

Anyway, you can handle exceptions inside a thread as you would do in a single-threaded application.

See http://msdn.microsoft.com/en-us/library/ms228965(v=VS.90).aspx for reference.


No, consider the following code:

try
{
   var t = new Thread(()=>
      {
          Thread.Sleep(5000);
          throw new Exception();
      });
   t.Start();
   //t.Join();
}
catch
{
    //you can't deal with exception here
    //even though you uncomment `t.Join`
}

Deal with exceptions in the child thread which the exceptions "belongs" to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜