日期:2014-05-19  浏览次数:21022 次

线程捕捉Exception的问题
下面这段代码,
                public   static   void   test()
                {
                        System.Threading.Thread   thread   =   new   System.Threading.Thread(new   System.Threading.ThreadStart(ExceptionMethod));
                        try
                        {
                                thread.Start();
                        }
                        catch   (System.Exception   ex)
                        {
                                Console.WriteLine(ex.Message);
                        }
                }

                public   static   void   ExceptionMethod()
                {
                              throw   new   Exception( "Error. ");
                }

会出错,原因是try捕捉不到thread   里的例外,有什么办法可以让try捕捉得到呢?

除了在ExceptionMethod方法里面加try外。

------解决方案--------------------
UP
------解决方案--------------------
如果用delegate的BeginInvoke完成异步,那么.Net会把Exception传递到调用线程:

delegate void Func();

public static void test()
{
try
{
Func func = new Func(ExceptionMethod);
IAsyncResult res = func.BeginInvoke(null, null);
func.EndInvoke(res);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
------解决方案--------------------
你在THREAD里面TRY

然后SEND MESSAGE算了...