Background Threads in ASP.NET with IRegisterObject

Running or spawning off some threads in ASP.NET is a fantastic way to get some work done faster. However, it is also a recipe for disaster if you are not careful. Interestingly enough, I ran across a blog posting by Phil Haack (no doubt you have heard of him), and in his discussion he talks about some reasons you may want to run long running threads in an ASP.NET application. While I do not wish to discuss the DO’s and DON’Ts of such code and the moral implications, it is an interesting topic none the less.

Regardless of that debate, Phil talks about the use of an interface called IRegisterObject which basically is a way to register an object with IIS and in turn IIS will call the stop method of any registered objects. This allows you to get a notification on any long running processes that its time to pack it in. In my own usage, this simply meant saving my progress and marking the item as “Disrupted” and it will be rerun when the application starts again.

It’s a simple, easy interface you can effectively take advantage of if you find yourself in the unknown waters of Long Running Threads in ASP.NET:

Capture

http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx

The “immediate” parameter indicates whether you have 30 seconds to stop still, or if you need to stop NOW. The Stop method will be called twice based on this behaviour.

To register and unregister your object call: HostingEnvironment.RegisterObject(this). In the stop method, once your process has been successfully stopped you should call HostingEnvironment.UnregisterObject(this) to signal that your process has stopped.