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 callingRemoveAll

    ? In my application, it is possible that one thread is reading data from HttpApplicationState

    while another thread can call RemoveAll

    .
  • 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?
+1


source to share


2 answers


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();

      

+2


source


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?

+1


source







All Articles