下面的类解决了这个问题:
/// <summary>
/// Extends the System.Threading.Tasks.Task by automatically throwing the first exception to the main application thread.
/// </summary>
public class TaskEx
{
public Task Task { get; private set; }
private TaskEx(Action action)
{
Task = Task.Factory.StartNew(action).ContinueWith((task) =>
{
ThrowTaskException(task);
});
}
public static TaskEx StartNew(Action action)
{
if (action == null)
{
throw new ArgumentNullException();
}
return new TaskEx(action);
}
public TaskEx ContinueWith(Action<Task> continuationAction)
{
if (continuationAction == null)
{
throw new ArgumentNullException();
}
Task = Task.ContinueWith(continuationAction).ContinueWith((task) =>
{
ThrowTaskException(task);
});
return this;
}
private void ThrowTaskException(Task task)
{
if (task.IsFaulted)
{
App.Current.Dispatcher.Invoke(new Action(() =>
{
throw task.Exception.InnerExceptions.First();
}));
}
}
}
现在我可以简单地使用以下代码(与 Task 类完全相同):
TaskEx.StartNew(() =>
{
// do something that may cause an exception
}).ContinueWith((task) =>
{
// then do something else that may cause an exception
}).ContinueWith((task) =>
{
// then do yet something else that may cause an exception
});
然而,与 Task 类不同的是,从这些线程之一抛出的任何异常都将被我的 DispatcherUnhandledException 事件处理程序自动捕获。