一般我们 WPF 中都加全局捕获, 避免出现异常导致崩溃.
- Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
- AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
- TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
但是, 一些比较耗时的操作, 我们放到线程中, 如果抛出了异常
- System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((p) =>
- {
- System.Threading.Thread.Sleep(1000);
- throw new Exception("bbb");
- }));
CurrentDomain.UnhandledException 会捕获到, 但是这种捕获方式显示错误后, 还是会导致程序崩溃.
后来研究了下, 想想换个线程方式.
- private async void Run()
- {
- await Task.Run(() =>
- {
- Thread.Sleep(1000);
- throw new Exception("bbb");
- });
- }
这种方式抛出异常后, 会被 DispatcherUnhandledException 捕获到, 这种异常可以 e.Handled=true, 不会崩溃.
来源: http://www.bubuko.com/infodetail-3368012.html