asp.net mvc3 request thread affinity
Asked Answered
F

1

10

I am using a proprietary IoC mechanism in my asp.net mvc3 application (on IIS7) that saves state in [ThreadStatic] fields and therefore relies on an assumption that HttpApplication.BeginRequest, HttpApplication.EndRequest and the whole synchronous execution of the (single) request they relate to are executed on the same thread.

Is that assumption correct?

Fanfani answered 1/1, 2012 at 21:7 Comment(0)
G
9

Is that assumption correct?

No, this assumption is not correct and there's evidence for it. The only reliable per request storage mechanism in ASP.NET is HttpContext.Items.

Never use [ThreadStatic] fields to store per-request values in an ASP.NET application. For example if you have an asynchronous controller you could very well have the engine draw one request from the thread pool to begin serving the request, then initiate an asynchronous operation relying on an IOCP (I/O Completion Port) and finally draw another thread from the pool to finish the request. So you could have 2 different threads serving the same HTTP request.

Absolutely never rely on the fact that the HTTP request will be served by the same thread.

This could be true in some cases for synchronous requests but remember that this is just an implementation detail. This could change without any notice from one version of .NET to another. You should never rely on it and never use [ThreadStatic] in ASP.NET. This could bite you very badly.

Gaberlunzie answered 1/1, 2012 at 22:49 Comment(3)
Is there an easy way to reproduce such a behavior?Ferris
Wow I'm very shocked by this answer, I really believed that ASP.NET MVC was processing every request per thread. Is it still the case with MVC 5 ? How do you explain that is is possible to set Thread.CurrentThread.CurrentCulture for multilingual application, if requests are not processed per thread ?Disharmony
@reddy As far as I know ASP.NET takes care of those objects (HttpContext, CurrentCulture, ...) and transfer them from one thread to the other one.Ferris

© 2022 - 2024 — McMap. All rights reserved.