In my asp.net
application, i want to cache some data in the HttpApplicationState
.
My code to set the data looks like this:
Application.Lock();
Application.Set("Name", "Value");
Application.UnLock();
When I read the documentation, it says that HttpApplicationState
is implicitly thread safe. But on many blogs it's written that we should use Application.Lock()
and Application.Unlock()
while writing data to the HttpApplicationState
.
On the other hand, I could not find any documentation which says that we should use lock while reading data from HttpApplicationState
or while clearing it (using Application.RemoveAll()
) method.
My questions are:
RemoveAll
? In my application, it's possible that one thread is reading a data from HttpApplicationState
whereas other thread could call RemoveAll
. HttpApplicationState
is possible from two different threads at the same time, should reading too not be thread safe?You only need the lock if you are doing more than one operation against the application state. In you case you are just doing one operation, so it's perfectly safe without the lock:
Application.Set("Name", "Value");
If you do more than one operation, and they rely on each other, you need the lock. For example:
Application.Lock();
string name = Application.Get("Name");
if (name == null) {
Application.Set("Name", "Value");
}
Application.UnLock();