C# - 没有捕获任务异常

时间:2012-10-23 00:57:24

标签: c#

我确信我做错了什么,但是当我尝试新的线程任务异常处理的这个例子时,我继续得到用户代码未处理的异常。代码的重点是展示如何捕获任务中的错误的示例。

链接:Task Exception Example

static void Main(string[] args)
        {
            var task1 = Task.Factory.StartNew(() =>
            {
                throw new MyCustomException("I'm bad, but not too bad!");
            });

            try
            {
                task1.Wait();
            }
            catch (AggregateException ae)
            {
                // Assume we know what's going on with this particular exception. 
                // Rethrow anything else. AggregateException.Handle provides 
                // another way to express this. See later example. 
                foreach (var e in ae.InnerExceptions)
                {
                    if (e is MyCustomException)
                    {
                        Console.WriteLine(e.Message);
                    }
                    else
                    {
                        throw;
                    }
                }

            }
        }

很可能用户错误只是不确定(使用Visual Studio 2012);

1 个答案:

答案 0 :(得分:14)

从您引用的页面:

  

注意

     

启用“Just My Code”时,Visual Studio会在某些情况下启用   在抛出异常并显示错误的行上中断   显示“异常未由用户代码处理”的消息。这个错误是   良性。您可以按F5继续并查看异常处理   这些例子中展示的行为。防止视觉   Studio打破第一个错误,只需取消选中“Just My   代码“工具,选项,调试,常规下的复选框。