Creating Dynamic Locks at Runtime in ASP.NET

Viewed 2555

Are the following assumptions valid for this code? I put some background info under the code, but I don't think it's relevant.

Assumption 1: Since this is a single application, I'm making the assumption it will be handled by a single process. Thus, static variables are shared between threads, and declaring my collection of lock objects statically is valid.

Assumption 2: If I know the value is already in the dictionary, I don't need to lock on read. I could use a ConcurrentDictionary, but I believe this one will be safe since I'm not enumerating (or deleting), and the value will exist and not change when I call UnlockOnValue().

Assumption 3: I can lock on the Keys collection, since that reference won't change, even if the underlying data structure does.

private static Dictionary<String,Object> LockList = 
    new Dictionary<string,object>();

private void LockOnValue(String queryStringValue)
{
    lock(LockList.Keys)
    {
        if(!LockList.Keys.Contains(queryStringValue))
        {
            LockList.Add(screenName,new Object());
        }
        System.Threading.Monitor.Enter(LockList[queryStringValue]);
    }
}

private void UnlockOnValue(String queryStringValue)
{
    System.Threading.Monitor.Exit(LockList[queryStringValue]);
}

Then I would use this code like:

LockOnValue(Request.QueryString["foo"])
//Check cache expiry
//if expired
    //Load new values and cache them.
//else
    //Load cached values
UnlockOnValue(Request.QueryString["foo"])

Background: I'm creating an app in ASP.NET that downloads data based on a single user-defined variable in the query string. The number of values will be quite limited. I need to cache the results for each value for a specified period of time.

Approach: I decided to use local files to cache the data, which is not the best option, but I wanted to try it since this is non-critical and performance is not a big issue. I used 2 files per option, one with the cache expiry date, and one with the data.

Issue: I'm not sure what the best way to do locking is, and I'm not overly familiar with threading issues in .NET (one of the reasons I chose this approach). Based on what's available, and what I read, I thought the above should work, but I'm not sure and wanted a second opinion.

2 Answers
Related