C# 异常处理(任务并行库).Net Framework 4.0 Beta 2
目前我正在尝试任务并行库的一些新功能, Net Framework 4.0 Beta 2随附 我的问题特别涉及TPL as中的异常处理 此处描述: 第一个示例(稍作修改): 根据文档,应该将异常传播回去 到调用的加入线程:C# 异常处理(任务并行库).Net Framework 4.0 Beta 2,c#,exception-handling,multithreading,C#,Exception Handling,Multithreading,目前我正在尝试任务并行库的一些新功能, Net Framework 4.0 Beta 2随附 我的问题特别涉及TPL as中的异常处理 此处描述: 第一个示例(稍作修改): 根据文档,应该将异常传播回去 到调用的加入线程:task1.Wait() 但我总是在以下时间内收到未处理的异常: var task1 = Task.Factory.StartNew(() => { throw new MyCustomException("I'm bad, but not too bad!")
task1.Wait()
但我总是在以下时间内收到未处理的异常:
var task1 = Task.Factory.StartNew(() =>
{
throw new MyCustomException("I'm bad, but not too bad!");
});
有人能向我解释一下原因吗,或者有人知道自Beta 2发布以来是否发生了一些变化吗?您的异常可能在到达try语句和相应的等待之前被抛出 试试这个:
static void Main(string[] args)
{
try
{
// Move this inside teh try block, so catch can catch any exceptions thrown before you get to task1.Wait();
var task1 = Task.Factory.StartNew(() =>
{
throw new Exception("I'm bad, but not too bad!"); // Unhandled Exception here...
});
task1.Wait(); // Exception is not handled here....
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
Console.WriteLine(e.Message);
}
}
Console.ReadLine();
}
答案在您链接的文章中: 启用“仅我的代码”时,可视 在某些情况下,工作室会在 抛出异常和 显示一条错误消息,其中显示 “用户代码未处理异常。” 这个错误是良性的。你可以按F5 继续并查看 异常处理行为 在这些例子中进行了演示。到 防止Visual Studio中断 第一个错误,只需取消选中 工具下的“仅我的代码”复选框, 选项、调试、常规
不幸的是,这并没有改变任何行为,仍然存在如上所述的未处理异常。只是保存了我的屁股!对于下一个来的人,请注意这是“取消选中”而不是“选中”!因为无法阅读怪异的“功能”而羞愧地垂下头。。。这是Visual Studio中的错误吗?
static void Main(string[] args)
{
try
{
// Move this inside teh try block, so catch can catch any exceptions thrown before you get to task1.Wait();
var task1 = Task.Factory.StartNew(() =>
{
throw new Exception("I'm bad, but not too bad!"); // Unhandled Exception here...
});
task1.Wait(); // Exception is not handled here....
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
Console.WriteLine(e.Message);
}
}
Console.ReadLine();
}