【发布时间】:2012-08-03 15:13:32
【问题描述】:
我在 TPL 编程方面遇到问题。
我在 [ http://stackoverflow.com/questions/7883052/a-tasks-exceptions-were-not-observed-either-by-waiting-on 上使用 @h4165f8ghd4f854d6f8h 解决方案时收到 UnobservedTaskException -the-task-or-accessi/11830087#11830087 ] 来处理异常但仍然得到 UnobservedTaskException。
我也在开始任务之前添加了以下代码:
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
e.SetObserved();
throw e.Exception;
};
但是 [ http://stackoverflow.com/questions/10874068/exception-thrown-in-task-thread-not-caught-by-unobservedtaskexception ] 告诉它不会捕获每个 TPL 未处理的异常。
我想传播异常直到到达堆栈顶部然后处理它。
有人可以帮帮我吗????
@乔恩斯基特
您好,我做了一个较小的复制,感谢您检查
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.tplTestOne();
}
public void tplTestOne()
{
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
e.SetObserved();
throw e.Exception;
};
Task tsk_1 = MyClassHere.createHandledTask(() =>
{
double x = 1;
x = (x + 1) / x;
}, false);
Task tsk_2 = MyClassHere.createHandledTask(() =>
{
double y = 0;
throw new Exception("forced_divisionbyzerodontthrowanymore_test"); // here -> System.Exception was unhandled by user code
}, true);
Task tsk_3 = MyClassHere.createHandledTask(() =>
{
double z = 1;
z = (z + 1) / z;
}, true);
Task tsk_4 = MyClassHere.createHandledTask(() =>
{
double k = 1;
k = (k + 1) / k;
}, true);
Console.ReadLine();
}
}
public static class MyClassHere
{
public static void waitForTsk(Task t)
{
try
{
t.Wait();
}
catch (AggregateException ae)
{
ae.Handle((err) =>
{
throw err;
});
}
}
public static void throwFirstExceptionIfHappens(this Task task)
{
task.ContinueWith(t =>
{
var aggException = t.Exception.Flatten();
foreach (var exception in aggException.InnerExceptions)
{
throw exception; // throw only first, search for solution
}
},
TaskContinuationOptions.OnlyOnFaulted); // not valid for multi task continuations
}
public static Task createHandledTask(Action action)
{
return createHandledTask(action, false);
}
public static Task createHandledTask(Action action, bool attachToParent)
{
Task tsk = null;
if (attachToParent)
{
TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
tsk = Task.Factory.StartNew(action, atp);
}
else
{
tsk = Task.Factory.StartNew(action);
}
tsk.throwFirstExceptionIfHappens();
return tsk;
}
}
谢谢
【问题讨论】:
-
这并不能证明我的盒子有问题......它只是运行。你在看什么?
-
您好,感谢您的关注。那里比这里最糟糕,因为在那一行没有出现异常: throw new Exception("forced_divisionbyzerodontthrowanymore_test"); // 这里 -> System.Exception 未被用户代码处理 。我在 Visual Studio 2010 环境中遇到此异常:System.Exception 未被用户代码处理
-
啊 - 我正在使用 .NET 4.5,它具有不同的行为......
-
使用 4.0 顺便说一句,4.5 忽略异常?
-
你也应该看到 ito:stackoverflow.com/questions/4238345/…
标签: c# exception task-parallel-library