如何处理Task.Factory.StartNew异常?

mon*_*str 6 c# exception-handling exception task-parallel-library

我这里有一些奇怪的问题.任何抛出的异常总是不能独立处理我如何尝试处理它.

我试试这个:

http://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx

private class MyCustomException : Exception
{
     public MyCustomException(String message) : base(message)
     {
     }
}

public static void Main()
{
   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;
           }
       }

    }
    Console.Read();
}
Run Code Online (Sandbox Code Playgroud)

这个:

http://dotnetcodr.com/2014/02/11/exception-handling-in-the-net-task-parallel-library-with-c-the-basics/

这个:

http://blogs.msdn.com/b/pfxteam/archive/2010/08/06/10046819.aspx

这个:

var task = Task.Factory.StartNew(() => this.InitializeViewModel(myViewModel));
task.ContinueWith(o => MyErrorHandler(task.Exception), TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)

并在StackOverflow上检查很多其他类似的问题.但它始终是相同的 - 不处理异常.它不是在这些原始代码片段上处理的!我觉得这里有点神奇......我在.Net Framework 4.0上工作

同时处理对我有用的异常的单一方法是:

        Task.Factory.StartNew(() =>
        {
            try
            {
                //do something that thrown exception
            }
            catch (Exception)
            {

            }
        });
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 7

如果您在Visual Studio中运行该示例代码,您确实会收到消息,MyCustomException was unhandled by user code并且Visual Studio将在该行中断开.

这并不意味着你的异常真的没有处理.这只是意味着,在默认情况下,Visual Studio中打破其上没有处理的异常里面的任务.您可以通过运行应用程序而无需调试来验证这一点(Ctrl-F5); 您会注意到您的异常按预期处理.

以下SO问题中更详细地描述了此问题: