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

}

method B()
{
 // getDBQuery
}

B 中的异常但未捕获。它在.net中合法吗?

4

2 回答 2

7

正确,来自线程的异常不会转发给调用者,线程应自行处理。

最普遍的答案是你不应该在这里使用(裸)线程。它效率不高,也不方便。

当您使用Task时,异常会在您调用Wait()或时存储并引发Result

于 2013-11-04T14:59:37.833 回答
4

When A is finished executing B might still be running as it is on an independent thread. For that reason it is impossible by principle for A to catch all exceptions that B produces.

Move the try-catch to inside of B. The Thread class does not forward exceptions.

Better yet, use Task which allows you to propagate and inspect exceptions.

于 2013-11-04T14:59:44.087 回答