在线程C#中抛出异常

Hiy*_*sat 5 c# multithreading

我有线程这样,在我看到示例链接文本后

ThreadStart _threadStart = new ThreadStart(delegate()
{
       try
       {
           threadFunction(httpContext);
       }
       catch (Exception ex)
       {
           throw ex;
       }
 });
 Thread _thread = new Thread(_threadStart);
  _thread.Start();
Run Code Online (Sandbox Code Playgroud)

当异常发生时,它不会在启动它的线程中重新抛出.那么我做错了什么或怎么做?

注意:感谢所有高级评论

Guf*_*ffa 7

抛出异常,但这只会结束线程.在启动它的线程中不会重新抛出异常.


Gus*_*ori 6

我认为问题的核心是要理解线程中发生的异常不会传递给调用线程进行处理.

例如,假设您有反叛方法:

private static void RebelWithoutACause()
{
    throw new NullReferenceException("Can't touch this!");
}
Run Code Online (Sandbox Code Playgroud)

假设您创建了一个在程序中调用此方法的新线程,并且作为一个安全的程序员,您决定将工作包含在一个try/catch块中:

private static void Main(string[] args)
{
    try
    {
        var thread = new Thread(RebelWithoutACause);
        thread.Start();
        thread.Join();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你在调试器中运行它,你会发现你永远不会到达catch块,而线程将被杀死,调试器会抱怨你有一个未处理的异常.

您需要选择如何处理异常,但需要在每个线程入口方法中进行处理.典型处理包括记录详细信息,通过UI通知用户,以及尽可能优雅地关闭应用程序.