开发者

HttpApplicationState - Why does Race condition exist if it is thread safe?

开发者 https://www.devze.com 2022-12-08 00:03 出处:网络
I just read an article that describes how HttpApplicationState has AcquireRead() / AcquireWrite() functions to manage concurrent access. It continues to explain, that in some conditions however we nee

I just read an article that describes how HttpApplicationState has AcquireRead() / AcquireWrite() functions to manage concurrent access. It continues to explain, that in some conditions however we need to use an explict Lock() and Unlock() on the Application object to avoid a Race condition.

I am unable to understand why a race condition should exist for Application state if concurrent access is implicitly handled by the object.

Could someone please explain this to me ? W开发者_StackOverflowhy would I ever need to use Application.Lock() and Application.Unlock() ? Thank You !


The AcquireRead and AcquireWrite methods are in the internal HttpApplicationStateLock class, so you don't use them yourself. They synchronise access, but only for a single read or write. From your code you use the Lock and Unlock methods if you need to synchronise access.

You would typically need to synchonise the access if you are changing something that is not a single read or write, like adding two application items that rely on each other, or first checking if an item exist and then add it:

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


HttpApplicationState - where the globally access variables those are visible to all the

users who are using the application. So in order to avoid the race condition while changing

the value of the variables. We need some precautionary, thats why we are using

Application.Lock() and after the job done releasing the same variable to others in the

queue using Application.Unlock()

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

精彩评论

暂无评论...
验证码 换一张
取 消