有了System.Threading.Tasks.Task<TResult>,我必须管理可能抛出的异常.我正在寻找最好的方法.到目前为止,我已经创建了一个基类来管理调用中的所有未捕获的异常.ContinueWith(...)
我想知道是否有更好的方法可以做到这一点.或者即使这是一个很好的方法.
public class BaseClass
{
protected void ExecuteIfTaskIsNotFaulted<T>(Task<T> e, Action action)
{
if (!e.IsFaulted) { action(); }
else
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
/* I display a window explaining the error in the GUI
* and I log the error.
*/
this.Handle.Error(e.Exception);
}));
}
}
}
public class ChildClass : BaseClass
{
public void DoItInAThread()
{
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew<StateObject>(() => this.Action())
.ContinueWith(e => this.ContinuedAction(e), context);
}
private void ContinuedAction(Task<StateObject> e)
{
this.ExecuteIfTaskIsNotFaulted(e, () => …Run Code Online (Sandbox Code Playgroud) 我试图了解在任务对象中引发但从未处理的异常发生了什么.
在MSDn上,据说:
如果您不等待传播异常的任务或访问其Exception属性,则在对任务进行垃圾回收时,将根据.NET异常策略升级异常.
所以我不太明白这些异常会以何种方式影响程序流程.我认为这些异常应该在垃圾收集后立即中断执行.但我无法设计这种行为.在以下代码段中,抛出的异常不会显示.
// Do something ...
Task.Run (()=> {throw new Exception("Exception in the task!");});
// Do something else
Run Code Online (Sandbox Code Playgroud)
请问,任何人都可以解释如何处理未处理的任务异常,以及它们如何影响程序流程.