0

是否有可能趕上意想不到的錯誤在全球範圍內的C#WPF應用程序 - C#4.0是否有可能趕上意想不到的錯誤在全球範圍內的C#WPF apllication - C#4.0

我發現DispatcherUnhandledException能趕上UI線程錯誤,但實際上我需要TPL線程。 UnhandledException能夠捕獲線程錯誤,但它仍然導致軟件終止。

因此,任何解決方案都可以捕獲線程中未處理的異常,而不是在UI線程中,並且仍然讓軟件運行不會終止。線程是TPL線程。 (任務並行庫)

+0

可能重複,以解決您的case.You做到這一點[如何使用任務並行庫時,處理所有未處理的異常? ](http://stackoverflow.com/questions/2707295/how-to-handle-all-unhandled-exceptions-when-using-task-parallel-library) – Jon

回答

1

的一部分從處理DispatcherUnhandledException你已經這樣做了添加到您的配置文件

<configuration> 
    <runtime> 
    <legacyUnhandledExceptionPolicy enabled="1"/> 
    </runtime> 
</configuration> 

這可以防止您的輔助線程的例外,從關閉應用程序。

+0

所以我可以使用這個和UnhandledException來捕獲錯誤,讓軟件繼續我是否正確?但我把它放在哪裏?它是wpf不是asp.net – MonsterMMORPG

+0

在你的app.config文件中不僅存在於ASP.Net應用程序中。它只會允許你在出現異常情況時不會退出應用程序。我不知道你將如何捕獲它們 –

+0

這是什麼配置文件,我沒有看到任何地方。我有app.xaml,但它給我出現錯誤 – MonsterMMORPG

1

您可以使用Custom Escalation Policy在TPL添加一個事件處理程序的靜態System.Threading.Tasks.TaskScheduler.UnobservedTaskException成員的

class Test 
    { 
     static void Main(string[] args) 
     { 
      // create the new escalation policy 
      TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) => 
      { 
       // mark the exception as being handled 
       eventArgs.SetObserved(); 
       // get the aggregate exception and process the contents 
       ((AggregateException)eventArgs.Exception).Handle(ex => 
        { 
         // write the type of the exception to the console 
         Console.WriteLine("Exception type: {0}", ex.GetType()); 
         return true; 
        }); 
       }; 
      // create tasks that will throw an exception 
      Task task1 = new Task(() => 
      { 
       throw new NullReferenceException(); 
      }); 
      Task task2 = new Task(() => 
      { 
       throw new ArgumentOutOfRangeException(); 
      }); 
      // start the tasks 
      task1.Start(); task2.Start(); 
      // wait for the tasks to complete - but do so 
      // without calling any of the trigger members 
      // so that the exceptions remain unhandled 
      while (!task1.IsCompleted || !task2.IsCompleted) 
      { 
       Thread.Sleep(500); 
      } 
      // wait for input before exiting 
      Console.WriteLine("Press enter to finish and finalize tasks"); 
      Console.ReadLine(); 
     } 
    } 
}