【发布时间】:2013-05-13 00:48:04
【问题描述】:
通常,对于我不希望抛出异常但会抛出异常的代码(即编程错误),我希望我的应用程序崩溃(这样它就不会损坏数据、向用户报告无效数据等)。 )。
在使用Tasks 时,是否有获得(接近)这种行为的最佳实践?我们已经为TaskScheduler.UnobservedTaskException 注册了一个处理程序。问题在于,这可能比导致意外异常的时间晚很多。
问题: 如果有的话我应该使用哪个选项:
我是否应该将我的
Tasks 操作包装在 try/catch 中,并在 catch 中升级我不期望的异常?如果是这样,我应该怎么做才能升级(即我想让它触发AppDomain.UnhandledException事件并终止。我是否应该在 ui 线程(这是一个 Winforms 应用程序)上附加一个延续 (
OnlyOnFaulted),如果它不是预期的异常,它会重新引发异常?有更好或更标准的方法吗?
这是 #1 的样子:
var t1 = Task.Factory.StartNew(() =>
{
try
{
string path = null; // Programming error. Should have been a valid string. Will cause System.ArgumentNullException below
using (FileStream fs = File.Create(path))
{
}
}
catch (System.IO.IOException) { throw; } // Expected possible exception
catch (System.UnauthorizedAccessException) { throw; }
catch
{
// Anything caught here is not an expected exception and should be escalated.
// But how?
}
});
下面是#2 的样子:
TaskScheduler uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var t1 = Task.Factory.StartNew(() =>
{
string path = null; // Programming error. Should have been a valid string. Will cause System.ArgumentNullException below
using (FileStream fs = File.Create(path))
{
}
});
t1.ContinueWith(t =>
{
Exception ex = t.Exception;
if (ex is IOException || ex is UnauthorizedAccessException) // Expected exceptions (do nothing)
return;
throw ex; // Not expected (escalate by rethrowing)
}, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiTaskScheduler);
【问题讨论】:
标签: c# exception-handling task-parallel-library