Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CallContext vs ThreadStatic

Tags:

c#

asp.net

What are differences between CallContext and ThreadStatic?

I've understood that in an ASP.NET environment data stored in CallContext could be persisted throughout the request until it ends while ThreadStatic may or may not work since the request may switch threads. I've also learned that the HttpContext is internally stored using the CallContext.

In a regular application they both seem to persist throughout the same thread call. When isn't this the case?


Edit: In the comments I learned that the call context is an abstraction over a thread static store. The ASP.NET framework explicitly moves the data from one thread to the next that is to handle one request. Other framework that wants to provide thread agility could do the same to for contextual storage.

like image 733
Cristian Libardo Avatar asked Nov 07 '08 19:11

Cristian Libardo


2 Answers

Very often a request will use the same thread throughout, but it certainly won't always be the case - ASP.NET exhibits thread agility. There's an old in-depth blog article about the matter from 2005, but as of .NET 4.5 things are rather better.

like image 67
Jon Skeet Avatar answered Sep 19 '22 19:09

Jon Skeet


Items stored as ThreadStatic are available to more than one request. IIS reuses the thread after a request is complete to process subsequent requests, it can even swap a request from one thread to another during processing. ASP.Net clears down the CallContext after each request.

like image 27
Martin Brown Avatar answered Sep 19 '22 19:09

Martin Brown