it:ad:iis:howto:thread_agility_versus_threadstatic_versus_callcontext

IT:AD:IIS:HowTo:Thread Agility versus ThreadStatic versus CallContext

Summary

Most developers don't know this, but under pressure IIS reserves the right to – during waiting for the return of async operations – reallocate a request's thread to another request.

Say whaaat?!!?

It's referred to as “Thread Agility”.

Therefore: * In an IIS environment, avoid using ThreadStatic like the plague. * Don't use CallContext either. * Use only HttpContext.

Of special concern is are at least common variables: Identity and EF DbContext.

Identity is ok, because the Identity is migrated at the same time as the HttpContext. So is Culture. CallContext is not.

It's possible EF5 used to store things on the thread 1), but doesn't anymore(?). I'm assuming they figured out how to do via HttpContext, in order to offer the new async functionality. The reason it's not possible that they EF changes threads in mid-commit, is that it would not be possible to commit more than once in an operation, commit… In fact, I frankly don't believe it does – as others have pointed out, Thread Affinity happens at specific page lifecycle moments and not in the middle of an operation.

And even if it does swap…it is irrelevant when considering whether to perform using multi-threading (eg using a PriorityThreadDispatcher (or similar)) to perform operations in an web app. The reasons are as follows:

  • Yes, IIS manages its threads, performing thread agility hot swapping.
  • No, the threads we spun up – even though from the same ThreadPool – are not managed by IIS. That's the important point. If they are not managed by IIS, nor can they be revoked/reassigned. You're safe to create a new ThreadStatic based UnitOfWorkContext, etc. Done.

References


  • /home/skysigal/public_html/data/pages/it/ad/iis/howto/thread_agility_versus_threadstatic_versus_callcontext.txt
  • Last modified: 2023/11/04 22:58
  • by 127.0.0.1