即在不同的线程抛出catch异常 [英] catch exception that is thrown in different thread
问题描述
我的一个方法(方法1
)产生一个新的线程。
该线程执行的方法(方法2
)和exectution期间抛出一个异常。
我需要在调用方法异常信息(方法1
)
One of my method (Method1
) spawns a new thread.
That thread execute a method (Method2
) and during exectution an exception is thrown.
I need to get that exception information on the calling method (Method1
)
有什么方法我能赶上这个例外在方法1
是在方法2
?
Is there someway I can catch this exception in Method1
that is thrown in Method2
?
推荐答案
在 .NET 4 及以上时,你可以使用任务< T>
类,而不是建立新的线程。然后你可以使用你的任务对象的 .Exceptions
属性来获取异常。
有两种方法做到这一点:
In .NET 4 and above, you can use Task<T>
class instead of creating new thread. Then you can get exceptions using .Exceptions
property on your task object.
There are 2 ways to do it:
-
在一个单独的方法://你在处理某些异常的任务的线程
class Program
{
static void Main(string[] args)
{
Task<int> task = new Task<int>(Test);
task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
Console.ReadLine();
}
static int Test()
{
throw new Exception();
}
static void ExceptionHandler(Task<int> task)
{
var exception = task.Exception;
Console.WriteLine(exception);
}
}
在同样的方法://你处理异常在来电者的线程
class Program
{
static void Main(string[] args)
{
Task<int> task = new Task<int>(Test);
task.Start();
try
{
task.Wait();
}
catch (AggregateException ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
static int Test()
{
throw new Exception();
}
}
需要注意的是,你得到的例外是 AggregateException
。所有真正的例外是通过菱 ex.InnerExceptions
属性。
Note that the exception which you get is AggregateException
. All real exceptions are availible through ex.InnerExceptions
property.
在 .NET 3.5 您可以使用下面的code:
In .NET 3.5 you can use the following code:
-
//你处理例外
在孩子线程
// You process exception in the child's thread
class Program
{
static void Main(string[] args)
{
Exception exception = null;
Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), Handler));
thread.Start();
Console.ReadLine();
}
private static void Handler(Exception exception)
{
Console.WriteLine(exception);
}
private static void SafeExecute(Action test, Action<Exception> handler)
{
try
{
test.Invoke();
}
catch (Exception ex)
{
Handler(ex);
}
}
static void Test(int a, int b)
{
throw new Exception();
}
}
或者//你处理在来电者的线程例外
class Program
{
static void Main(string[] args)
{
Exception exception = null;
Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), out exception));
thread.Start();
thread.Join();
Console.WriteLine(exception);
Console.ReadLine();
}
private static void SafeExecute(Action test, out Exception exception)
{
exception = null;
try
{
test.Invoke();
}
catch (Exception ex)
{
exception = ex;
}
}
static void Test(int a, int b)
{
throw new Exception();
}
}
这篇关于即在不同的线程抛出catch异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!