【发布时间】:2009-04-22 17:57:06
【问题描述】:
我知道为什么,但我想问一下是否有人很好地理解了为什么线程内引发的异常不会被启动它的代码捕获。这里有一些非常简单的代码来说明我的意思:
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 我会很安全,但我发现事实并非如此(它使我的一项服务崩溃)。
【问题讨论】:
-
奇怪了,我刚才也准备发一个类似的帖子了。
-
我确定我有异常冒泡到调用线程。虽然我没有使用线程池。只是 Thread T = new Thread(new ThreadStart( delegate() { Console.WriteLine("Crash !"); DoCrashyThingy(); } )); T.Start();
-
我很容易错了,我的大部分工作都是这个可怕的单线程庞然大物..
标签: c# multithreading try-catch