简体   繁体   English

catch块在另一个线程中没有捕获异常

[英]catch block not catching exception in another thread

method A()
{
  try
  {
    Thread t = new Thread(new ThreadStart(B));
    t.Start();
  }
  catch(exception e)
  {
    //show message of exception
  }      

}

method B()
{
 // getDBQuery
}

a exception in B but not catched. B中的例外但没有捕获。 does it legal in .net? 它在.net中合法吗?

Correct, exceptions from a Thread are not forwarded to the caller, the Thread should handle this by itself. 正确,Thread中的异常不会转发给调用者,Thread应该自己处理。

The most general answer is that you should not be using a (bare) Thread here. 最一般的答案是你不应该在这里使用(裸)线程。 It's not efficient and not convenient. 它效率不高,不方便。

When you use a Task , the exception is stored and raised when you cal Wait() or Result . 使用任务时 ,在调用Wait()Result时会存储并引发异常。

When A is finished executing B might still be running as it is on an independent thread. A完成执行时, B可能仍然在独立线程上运行。 For that reason it is impossible by principle for A to catch all exceptions that B produces. 因此, A 原则上不可能捕获B产生的所有异常。

Move the try-catch to inside of B . 将try-catch移动到B内部。 The Thread class does not forward exceptions. Thread类不转发异常。

Better yet, use Task which allows you to propagate and inspect exceptions. 更好的是,使用允许您传播和检查异常的Task

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM