1

c#WPFアプリケーションで予期しないエラーをグローバルにキャッチすることは可能ですか?c#4.0

DispatcherUnhandledExceptionがUIスレッドエラーをキャッチできたことがわかりましたが、実際にはTPLスレッドが必要です。UnhandledExceptionはスレッドエラーをキャッチできましたが、それでもソフトウェアが終了していました。

したがって、UIスレッド以外のスレッドで未処理の例外をキャッチし、ソフトウェアを実行させても終了しないソリューション。スレッドはTPLスレッドです。(タスク並列ライブラリ)

4

2 に答える 2

2

すでに行った処理の一部を構成DispatcherUnhandledExceptionファイルに追加します

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

これにより、セカンダリ スレッドの例外によってアプリケーションがシャットダウンされるのを防ぐことができます。

于 2011-10-22T12:52:37.040 に答える
1

Custom Escalation PolicyTPL で使用してケースに対処できます。これを行うには、静的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();
        }
    }
}
于 2011-10-22T18:40:05.627 に答える