3

Does BeginRequest and EndRequest for an ASP.NET HttpApplication always occur on the exact same thread for a given HTTP request from a client?

The reason I ask is that I am seeing some very strange behavior where a ThreadStatic variable is not null inside of an Init method for an IHttpModule.

I set this ThreadStatic variable to a value on BeginRequest and null it on EndRequest.

However, my IHttpModule Init method should be called outside of the BeginRequest/EndRequest period, so the only way I can think of that this ThreadStatic variable would have a value when my Init method is called is if EndRequest occurs on a different thread than BeginRequest and thus the value is still not null later on when ASP .NET tries to use that same thread to create a new HttpApplication instance...

I am running IIS 7 in integrated mode.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jeff
  • 35,755
  • 15
  • 108
  • 220

3 Answers3

3

Does BeginRequest and EndRequest for an ASP .NET HttpApplication always occur on the exact same thread for a given HTTP request from a client?

No. There are options to perform asynchronous operations in the request leading to the end of the request being handled on a different thread. This is not the normal case.

See the Async attribute of @Page directive: http://msdn.microsoft.com/en-us/library/ydy4x04a.aspx

For an introduction to using asynchronous pages, see this MSDN Magazine article: "Asynchronous Pages in ASP.NET 2.0".

Richard
  • 106,783
  • 21
  • 203
  • 265
1

The funny thing is I've made this mistake before, so I should know better...but alas.

ThreadStatic members need to be STATIC. It really should throw a compiler error if it's not...

Jeff
  • 35,755
  • 15
  • 108
  • 220
0

No, as per Richard's answer.

As an aside, you're supposed to "share" variables between HTTP Modules via HttpContext.Current.Items. In the case of [ThreadStatic], due to thread agility in ASP.NET it's not guaranteed that your code will start and finish on the same thread. So, ThreadStatic isn't such a great idea in ASP.NET.

It's worth saying that EndRequest will always execute with the same HttpContext.

This seems to be the definitive post on using [ThreadStatic] verses HttpContext http://piers7.blogspot.co.nz/2005/11/threadstatic-callcontext-and_02.html

Scott Hanselman also posted on the subject:
http://www.hanselman.com/blog/ATaleOfTwoTechniquesTheThreadStaticAttributeAndSystemWebHttpContextCurrentItems.aspx

And Jon Skeet has a good SO answer here too:
CallContext vs ThreadStatic

Community
  • 1
  • 1
Dave Transom
  • 4,085
  • 3
  • 21
  • 22