【发布时间】:2014-02-26 13:20:40
【问题描述】:
请看下面的代码-
static void Main(string[] args)
{
// Get the task.
var task = Task.Factory.StartNew<int>(() => { return div(32, 0); });
// For error handling.
task.ContinueWith(t => { Console.WriteLine(t.Exception.Message); },
TaskContinuationOptions.OnlyOnFaulted);
// If it succeeded.
task.ContinueWith(t => { Console.WriteLine(t.Result); },
TaskContinuationOptions.OnlyOnRanToCompletion);
Console.ReadKey();
Console.WriteLine("Hello");
}
private static int div(int x, int y)
{
if (y == 0)
{
throw new ArgumentException("y");
}
return x / y;
}
如果我在发布模式下执行代码,输出是“发生一个或多个错误”,一旦我按下“Enter”键,也会显示“Hello”。如果我在调试模式下运行代码,输出和release模式一样,但是在IDE中调试时,控件执行该行时会出现IDE异常信息(“Unhandled exception in user code”)
throw new ArgumentException("y");
如果我从那里继续,程序不会崩溃并显示与发布模式相同的输出。这是处理异常的正确方法吗?
【问题讨论】:
-
考虑切换到 async/await:这是一种更容易读写的语法,尤其是在处理异常时。
-
@AnirbanPaul,您可能希望根据您的要求更新问题:VS2010 和 .Net 4.0,就像您在 here 所做的那样。
标签: c# .net task-parallel-library task