try / catch语句和线程 [英] Try/Catch and threading
问题描述
我有一个想法,为什么,但我想问,如果有人对为什么一个线程中引发的异常永远不会被启动它的代码抓到一个很好的把握。下面是一些非常简单的代码来证明我的意思:
I have an idea why but I'd like to ask if someone has a good grasp on why the exception raised inside a thread is never caught by the code that started it. Here's some very simple code to demonstrate what I mean:
using System;
using System.Collections.Generic;
using System.Threading;
namespace TestCrash
{
class Program
{
private static void Crash(object control)
{
AutoResetEvent are = (AutoResetEvent)(((object[])control)[0]);
are.Set();
throw new Exception("Burn baby burn");
}
static void Main(string[] args)
{
try
{
List<WaitHandle> waitHandles = new List<WaitHandle>();
for (int i = 0; i < 100; i++)
{
AutoResetEvent are = new AutoResetEvent(false);
waitHandles.Add(are);
object[] procControl = new object[] { are };
ThreadPool.QueueUserWorkItem(Crash, procControl);
WaitHandle.WaitAll(waitHandles.ToArray());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
我天真地认为,通过具有的try / catch我会很安全的,但我发现硬盘的方式,它是不是这样的(这是崩溃的我的服务之一)。
I naively thought that by having the try/catch I would be safe, but I found out the hard way that it is not the case (it is crashing one of my services).
推荐答案
好一般,你已经不知道从哪里始发线将是异常在新线程抛出的时间 - 为什么会是线程到处乱扔等待?例外
Well in general, you've no idea where the originating thread will be by the time the exception is thrown in the new thread - why would it be waiting around for the thread to throw an exception?
思所涉及的协议栈 - 当一个异常被抛出,这是不言而喻堆栈,直到它到达一个合适的catch块。新的线程有一个完全独立的堆栈来创建线程,所以它永远不会达到创建线程的堆栈catch块。
Think of the stacks involved - when an exception is thrown, it goes up the stack until it reaches an appropriate catch block. The new thread has a completely separate stack to the creating thread, so it'll never reach the catch block in the creating thread's stack.
编辑:当然,你可以设计你的系统,使创建线程的没有的等待其他事情发生 - 有点像消息回路Windows窗体应用程序。那么新的线程可以捕获异常,并发送一条消息给创建线程,那么这可能与该异常处理。这是不正常的设置,虽然 - 你必须做这一切明确
Of course, you could design your system so that the creating thread did wait for other things to happen - a bit like the message loop in a Windows Forms application. The new thread could then catch the exception and send a message to the creating thread, which could then deal with the exception. That isn't the normal setup though - you have to do it all explicitly.
这篇关于try / catch语句和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!