zoukankan      html  css  js  c++  java
  • WPF 线程中异常导致程序崩溃

    一般我们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,不会崩溃。

     .net framework 4.0中没有Task.Run怎么办,可以用Task.Factory.StartNew();

  • 相关阅读:
    Address already in use: JVM_Bind:80 异常的解决办法
    Spring(转载二)
    Spring(转载一)
    mybatis(二)
    mybatis(一)
    存储过程(二)
    存储过程(一)
    web过滤器
    请求转发和请求重定向
    JavaWeb(二)
  • 原文地址:https://www.cnblogs.com/czly/p/11858644.html
Copyright © 2011-2022 走看看