Is HttpApplicationState.RemoveAll () thread safe?
In my application, asp.net
I want to cache some data in a HttpApplicationState
.
My code for setting data looks like this:
Application.Lock();
Application.Set("Name", "Value");
Application.UnLock();
When I read the documentation, it says that it is HttpApplicationState
implicitly thread-safe. But it is written in many blogs that we should use Application.Lock()
and Application.Unlock()
when the data in the record HttpApplicationState
.
On the other hand, I couldn't find any documentation that says we should use a lock when reading data from HttpApplicationState
or when clearing it (using a method Application.RemoveAll()
).
My questions:
- Shouldn't we be concerned about thread safety when calling
RemoveAll
? In my application, it is possible that one thread is reading data fromHttpApplicationState
while another thread can callRemoveAll
. - In this case, when reading and clearing is
HttpApplicationState
possible from two different threads at the same time, reading shouldn't be thread safe either?
source to share
You only need blocking if you are performing multiple operations against application state. In this case, you are just doing one operation, so it is completely safe without blocking:
Application.Set("Name", "Value");
If you are performing multiple operations and they rely on each other, you need a lock. For example:
Application.Lock();
string name = Application.Get("Name");
if (name == null) {
Application.Set("Name", "Value");
}
Application.UnLock();
source to share
As far as I can tell, RemoveAll is thread safe as it calls the Clear method internally. The Clear method calls HttpApplicationStateLock.AcquireWrite and then calls base.BaseClear and finally releases the lock.
Also take a look at HttpApplicationState - Why is there a race condition if it is thread safe?
source to share