Uncaught exceptions in Task threads will kill IIS – even with WCF error handling

Yes, all unhandled exceptions will kill the IIS worker process, but in WCF you can tag an IErrorHandler onto your service behavior and all unhandled exceptions will be neatly taken care of. Unless that exception is thrown from a factory task, in which case the error handler is bypassed and the worker process is killed.

So this code:

public ServiceResponse OnBoardClient(Client newClient) {
  if (IsValid(newClient)) {
    var client = newClient;
    Task.Factory.StartNew(() => OnBoardClientInternal(client));
  }
  // etc.
}

private static void OnBoardClientInternal(Client newClient) {
  var zero = 0;
  var dbz = 10 / zero;
}

– will throw a System.AggregateException in the TaskExceptionHolder.Finalize() method and it will take down the IIS worker process with it (as described in this StackOverflow question). Of course this also kills any other connections being handled by the worker process.

This is in-line with the expected behaviour for ASP.NET applications:

“Exceptions that occur in the context of a request do not cause the worker process to end. However, unhandled exceptions outside the context of a request, such as exceptions on a timer thread or in a callback function, cause the worker process to end”.

So the WCF error handler only applies within the request-response context, and within task code you need to explicitly add error handling:

private static void OnBoardClientInternal(Client newClient)

{
  try {
    var zero = 0;
    var dbz = 10 / zero;
  } catch (Exception ex) {
    // etc.
  }
}
- which can call into your error handler's HandleError method (if your scenario warrants consistent error handling).
posted on Friday, September 30, 2011 11:42 AM
This article is part of the GWB Archives. Original Author: gwbarchive

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.