2

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:

  1. Should not we take care of thread-safety when we are calling RemoveAll? In my application, it's possible that one thread is reading a data from HttpApplicationState whereas other thread could call RemoveAll.
  2. In this case when reading and clearing HttpApplicationState is possible from two different threads at the same time, should reading too not be thread safe?
Learner
  • 4,661
  • 9
  • 56
  • 102

2 Answers2

3

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();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

As far as I can tell, the RemoveAll is thread safe as it calls the Clear method internally. The Clear method calls HttpApplicationStateLock.AcquireWrite and then calls the base.BaseClear and finally releases the lock.

Also have a look at HttpApplicationState - Why does Race condition exist if it is thread safe?

Community
  • 1
  • 1
Pieter Germishuys
  • 4,828
  • 1
  • 26
  • 34
  • 1. What if there is a situation when multiple threads are already 'reading' the HttpApplicationState when some other thread calls the 'RemoveAll'? Or other way round? 2. Even Application.Set() method acquires the lock internally. But still its recommended to use Application.Lock and UnLock. So for the similar reasons, why don't we need (or not recommended) to use the lock when we call RemoveAll? – Learner Mar 26 '13 at 05:56
  • The complete object is thread safe as stated by http://msdn.microsoft.com/en-us/library/system.web.httpapplicationstate.aspx. Just looking at the code using ILSpy, you will see that most of the operations have locks around them. i.e. public object Get(string name) { object result = null; this._lock.AcquireRead(); try { result = base.BaseGet(name); } finally { this._lock.ReleaseRead(); } return result; } – Pieter Germishuys Mar 26 '13 at 06:02