Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to care about thread-safety in ASP.NET with AJAX?

The question is, is it possible that requests for the same session are executed from multiple threads? Are methods in ASP.NET reentrant? Especially we are using AJAX which means that asychronous requests are taking place.

Would this mean to place locks around operations on objects placed inside the session?

I know that locks are essential when handling static and application wide variables, but the question is is the same true for session objects?

like image 784
codymanix Avatar asked Dec 17 '10 10:12

codymanix


1 Answers

ASP.NET normally uses one thread per request. It can use more than one thread, e.g. when serving asynchronous pages, but even then only one thread will be processing the request at any given time.

It's safe to use the session state from multiple threads, however, because accesses to the session object are serialized. From MSDN:

What if other pages attempt to concurrently access the session state? In that case, the current request might end up working on inconsistent data, or data that isn't up to date. Just to avoid this, the session state module implements a reader/writer locking mechanism and queues the access to state values. A page that has session-state write access will hold a writer lock on the session until the request terminates.

like image 72
Frédéric Hamidi Avatar answered Sep 28 '22 05:09

Frédéric Hamidi