ASP.NET thread switching


Home | Blog | CSLA .NET | CSLA Store

17 January 2006

In a recent entry there was a comment pointing to

this article, which discusses the way ASP.NET uses threads – a fact that has serious ramifications on software design.

<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” /> 

It made me do some serious thinking/research, because CSLA .NET uses various elements of the Thread object, including the CurrentPrincipal, thread-local storage and (in 2.0) the culture properties. My fear was that if the thread can switch “randomly” during page processing, then how can you count on any of these elements from the Thread object?   Scott Guthrie from Microsoft clarified this for me on a couple key points.   First, ASP.NET doesn’t change your thread at “random” or “without warning” (phrases I’d used in describing my worries). It changes it only in a clearly defined scenario. Specifically, when your thread performs an async IO operation. Scott points out that this is perhaps most common in a page that takes advantage of the new async page capability, or within a HttpModule that uses any async IO.   In other words, normal web pages really aren’t subject to this issue at all. It only occurs in relatively advanced scenarios. And you, as the developer, should know darn well when you invoke an async operation; thus you know when you open yourself up for thread switching.   Still, I wanted to make sure the Business Objects book didn’t go down a bad path with the Thread object. But Scott clarified further.   ASP.NET ensures that, even if they switch your thread, the CurrentPrincipal and culture properties from the original thread carry forward to the new thread. This is automatic, and you don’t need to worry about losing those values. Whew!   However, thread-local storage doesn’t carry forward. If you use that feature of the Thread object in ASP.NET code you could be in trouble. This did cause me to rework some code in the book and in CSLA .NET. Specifically CSLA .NET 2.0 now detects whether it is running in ASP.NET or not and uses either thread-local storage or HttpContext.Current.Items to maintain its context data.   I also went the rest of the way and created a Csla.ApplicationContext.User property that gets and sets the user’s principal on either the Thread or HttpContext based on whether the code is running in ASP.NET or not. This allows you to write code in your UI and objects and other libraries without worrying about whether it might run inside our outside ASP.NET at some point. Certainly for mobile business objects this is very important! They can (and often do) run in both a smart client and ASP.NET environment within the same application.