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

Question: is it possible that requests for the same session are executed from several threads? Are methods in ASP.NET reentrant? We especially use AJAX, which means that asynchronous requests are occurring.

Will this mean to block operations on objects placed inside the session?

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

+7
source share
2 answers

Typically, ASP.NET uses one thread for each request. It can use multiple threads, for example. when serving asynchronous pages , but even then only one thread will process the request at any given time.

It is safe to use session state from multiple threads, however, since access to the session object is serialized. From MSDN :

What if other pages try to access session state at the same time? In this case, the current query may ultimately run on inconsistent data or data that is not relevant. To avoid this, the session state module implements a read / write lock device and queues access to state values. A page that has write access to session state records holds a write lock on the session until the request completes.

+3
source

Question: is it possible that requests for the same session are executed from several threads?

If you use an HTTP session inside your page, requests for the same session will be queued using the ASP.NET engine. They will never work in parallel. For example, if you send multiple AJAX requests to any ASP.NET page that uses a session, these requests will be executed sequentially.

If you are not using a session, multiple concurrent requests will be executed in parallel.

+2
source

All Articles