Thread Exception Handling (Excerpt from WWW)

来源:互联网 发布:枕头哪个牌子最好 知乎 编辑:程序博客网 时间:2024/06/05 07:26

Exception Handling

Any try/catch/finally blocks in scope when a thread is created are of no relevance once the thread starts executing. Consider

the following program:

public static void Main() {

  try {
    new Thread (Go).Start();
  }
  catch (Exception ex) {
    // We'll never get here!
    Console.WriteLine ("Exception!");
  }

  static void Go() { throw null; }
}

The try/catch statement in this example is effectively useless, and the newly created thread will be encumbered with an

unhandled NullReferenceException. This behavior makes sense when you consider a thread has an independent execution path. The

remedy is for thread entry methods to have their own exception handlers:

public static void Main() {
   new Thread (Go).Start();
}

static void Go() {
  try {
    ...
    throw null;      // this exception will get caught below
    ...
  }
  catch (Exception ex) {
    Typically log the exception, and/or signal another thread
    that we've come unstuck
    ...
  }
From .NET 2.0 onwards, an unhandled exception on any thread shuts down the whole application, meaning ignoring the exception

is generally not an option. Hence a try/catch block is required in every thread entry method – at least in production

applications – in order to avoid unwanted application shutdown in case of an unhandled exception.