How to prevent an exception in a background thread from terminating an application?

后端 未结 5 1125
我寻月下人不归
我寻月下人不归 2020-11-29 22:33

I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 22:55

    Here is a great blog post about this problem: Handling "Unhandled Exceptions" in .NET 2.0

    IMO it would be right to handle exceptions in background threads manually and re-throw them via callback if necessary.

    delegate void ExceptionCallback(Exception ex);
    
    void MyExceptionCallback(Exception ex)
    {
       throw ex; // Handle/re-throw if necessary
    }
    
    void BackgroundThreadProc(Object obj)
    {
       try 
       { 
         throw new Exception(); 
       }
       catch (Exception ex)
       { 
         this.BeginInvoke(new ExceptionCallback(MyExceptionCallback), ex); 
       }
    }
    
    private void Test()
    {
       ThreadPool.QueueUserWorkItem(new WaitCallback(BackgroundThreadProc));
    }
    

提交回复
热议问题