HttpApplicationState - Why is there a race condition if it is thread safe?

I just read an article that describes how HttpApplicationState has functionality AcquireRead() / AcquireWrite()

to manage concurrency. He goes on to explain that in certain circumstances we need to use ekspliment Lock()

and Unlock()

on the Application object, in order to avoid race conditions.

I can't figure out why a race condition should exist for the application state if concurrency is handled implicitly by an object.

Can someone explain this to me? Why would I ever use Application.Lock()

and Application.Unlock()

? Thank!

+2


source to share


2 answers


The AcquireRead and AcquireWrite methods are in the inner class HttpApplicationStateLock, so you don't use them yourself. They sync access, but only for one read or write. From code, you use lock and unlock methods if you need to sync access.

You usually need to synchronize access if you are changing something that is neither read nor write, such as adding two elements of the application that rely on each other, or first checking if an element exists and then adding it:



Application.Lock()
if (Application["info"] == null) {
   Application.Add("info", FetchInfoFromDatabase());
}
Application.Unlock();

      

+3


source


HttpApplicationState - where global access variables are visible to everyone

users who are using the application. Therefore, to avoid race conditions when changing

the value of the variables. We need some precautions, so we use



Application.Lock () and after executing a job that released the same variable to other users in

using Application.Unlock ()

Application.Lock()
Application("VisitorCount") = Convert.ToInt32(Application("VisitorCount")) + 1
Application.UnLock()

      

+1


source







All Articles