首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

线程捕捉Exception的有关问题

2012-01-05 
线程捕捉Exception的问题下面这段代码,publicstaticvoidtest(){System.Threading.ThreadthreadnewSystem.

线程捕捉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算了...

热点排行