C# - 没有捕获任务异常

sca*_*cci 2 c#

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

链接:任务例外示例

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;
                    }
                }

            }
        }
Run Code Online (Sandbox Code Playgroud)

最有可能的用户错误只是不确定是什么(使用Visual Studio 2012);

may*_*ewr 14

从您引用的页面:

注意

启用"Just My Code"时,Visual Studio在某些情况下会在抛出异常的行上中断,并显示一条错误消息,指出"异常不由用户代码处理".这个错误是良性的.您可以按F5继续并查看这些示例中演示的异常处理行为.要防止Visual Studio在第一个错误中出现问题,只需取消选中Tools,Options,Debugging,General下的"Just My Code"复选框.