Pregunta

My application stores two related bits of data in application state. Each time I read these two values, I may (depending on their values) need to update both of them.

So to prevent updating them while another thread is in the middle of reading them, I'm locking application state.

But the documentation for HttpApplicationState.Lock Method really doesn't tell me exactly what it does.

For example:

  1. How does it lock? Does it block any other thread from writing the data?

  2. Does it also block read access? If not, then this exercise is pointless because the two values could be updated after another thread has read the first value but before it has read the second.

In addition to preventing multiple threads from writing the data at the same time, it is helpful to also prevent a thread from reading while another thread is writing; otherwise, the first thread could think it needs to refresh the data when it's not necessary. I want to limit the number of times I perform the refresh.

¿Fue útil?

Solución

Looking at the code is locking only the write, not the read.

public void Lock()
{
    this._lock.AcquireWrite();
}
public void UnLock()
{
    this._lock.ReleaseWrite();
}
public object this[string name]
{
    get
    {
        return this.Get(name);
    }
    set
    {
        // here is the effect on the lock
        this.Set(name, value);
    }
}
public void Set(string name, object value)
{
    this._lock.AcquireWrite();
    try
    {
        base.BaseSet(name, value);
    }
    finally
    {
        this._lock.ReleaseWrite();
    }
}

public object Get(string name)
{
    object obj2 = null;
    this._lock.AcquireRead();
    try
    {
        obj2 = base.BaseGet(name);
    }
    finally
    {
        this._lock.ReleaseRead();
    }
    return obj2;
}

The write and the read is thread safe, meaning have all ready the lock mechanism. So if you going on a loop that you read data, you can lock it outside to prevent other break the list.

Its also good to read this answer: Using static variables instead of Application state in ASP.NET

Its better to avoid use the Application to store data, and direct use a static member with your lock mechanism, because first of all MS suggest it, and second because the read/write to application static data is call the locking on every access of the data.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top