在单独的线程上捕获未处理的异常

在单独的线程上捕获未处理的异常

本文介绍了在单独的线程上捕获未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下事件来捕获主UI线程中的未处理的异常。

I am using the following event to catch unhandled exceptions in the main UI thread.

Application.ThreadException

不幸的是,它不能在单独的线程中捕获那些未处理的错误。我知道

Unfortunately, it does not catch those unhandled errors in seperate threads. I am aware of

AppDomain.CurrentDomain.UnhandledException

但是,这似乎是在触发时关闭应用程序,而前者没有。

However, this seems to shut down the application upon triggering, where as the former does not.

有没有办法在单独的线程处理未处理的异常,而没有应用程序关闭?

Is there a way to deal with unhandled exceptions on separate threads, without the application closing?

推荐答案

@Ani已经回答了你的问题。虽然我不同意线程中未处理的异常终止应用程序。使用线程通常意味着您有某种服务器应用程序。把它弄掉可能会导致很多愤怒的用户。

@Ani have already answered your question. Although I don't agree that unhandled exceptions in threads should terminate applications. Using threads usually means that you have some kind of server application. Bringing it down could result in a lot of angry users.

我已经写了一小段关于正确的异常处理:

I've written a small piece about proper exception handling: http://blog.gauffin.org/2010/11/do-not-catch-that-exception/

你应该总是捕获线程的异常。我通常使用以下模式:

You should always catch exceptions for threads. I usually use the following pattern:

  void ThreadMethod(object state)
  {
      try
      {
          ActualWorkerMethod();
      }
      catch (Exception err)
      {
          _logger.Error("Unhandled exception in thread.", err);
      }
  }

  void ActualWorkerMethod()
  {
      // do something clever
  }

通过将逻辑移动到一个单独的方法中,找到不能正确处理异常的线程方法要容易得多,只需保持try /在线程方法中catch块。

It's a whole lot easier to find thread methods that doesn't handle exceptions properly by moving the logic into a seperate method and just keep the try/catch block in the thread method.

这篇关于在单独的线程上捕获未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!