Sep 23 2009

ThreadStatic gotcha with ASP.Net

Category: .NetRory Primrose @ 06:40

I had a requirement recently in a service implementation that business rules at any point throughout the execution of a service request could determine a message to return in the header of the response. Because these circumstances don’t affect the execution of the request (no exception is thrown), I needed a loosely coupled way of recording all the required messages and handling them higher up the stack.

Storing data against the executing thread was the obvious solution. I considered manually storing information in the context data of the thread, but then thought this would be a great opportunity to use the ThreadStaticAttribute. I coded this up and it all seemed to work well.

Yesterday a bug was raised against this code because messages unrelated to the service request were being returned. I looked at the code and rechecked the ThreadStatic documentation. It shouldn’t be possible, but it was definitely happening.

I quickly realised that the thread must be being reused across multiple service requests. This reminded me that ASP.Net uses a ThreadPool and it would not be doing any clean up of ThreadStatic data as it reused an existing thread for a new service request.

The simple fix was to reset the ThreadStatic reference when the response is generated.

Tags:

Comments (2) -

1.
jgorlick jgorlick United States says:

The ThreadStatic documentation is not what you should be consulting in this case.  You should look at the hosting model's documentation.  ASP.NET and ThreadStatic don't mix.

Your solution only fixes the issue of being switched onto a thread that has a previous runner's data.  ASP.NET will also switch a runner onto and off of threads mid stream.  ASP.NET provides a context that is safe for its threading model for this reason.

2.
Rory Rory Australia says:

Thanks for the comment. I'll have to look into this some more.

The only issue I have with using ASP.Net host specific logic is that it ties the business implementation to that hosting platform. Realistically this shouldn't be a problem as it is in IIS in this case and not expected to be used anywhere else. I don't like loosing that flexibility though.

What I really should do loosely couple that logic and drop in an ASP.Net implementation.

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading