我有示例代码:
class Program
{
static void Main()
{
var a = new AsyncClass();
try
{
a.DoWork();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Main Exception");
}
}
private class AsyncClass
{
internal void DoWork()
{
Console.WriteLine("DoWork begin");
var task = new Task(TaskMethod);
task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.WriteLine("DoWork end");
}
static void ExceptionHandler(Task task)
{
Console.WriteLine("ExceptionHandler begin");
var exception = task.Exception;
if(exception != null)
{
Console.WriteLine("ExceptionHandler Exception");
throw exception;
}
Console.WriteLine("ExceptionHandler end");
}
private void TaskMethod()
{
Console.WriteLine("TaskMethod begin");
Thread.Sleep(TimeSpan.FromSeconds(10));
throw new InvalidOperationException("test ex!");
}
}
}
结果:
问题是: 如何捕获任务中抛出的主线程异常(在真实应用程序中我将使用全局异常收集,所以我不想在ContinueWith中处理异常)? 问题是,我的任务不应该等待,因为它无限循环,主线程在启动任务后继续自己的工作 - 任务不应该阻止主线程的执行。