Kendrick Kendrick - 1 month ago 7x
C# Question

Creating Dynamic Locks at Runtime in ASP.NET

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


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)
LockList.Add(screenName,new Object());

private void UnlockOnValue(String queryStringValue)

Then I would use this code like:

//Check cache expiry
//if expired
//Load new values and cache them.
//Load cached values

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.


Your current solution looks pretty good. The two things I would change:

1: UnlockOnValue needs to go in a finally block. If an exception is thrown, it will never release its lock.

2: LockOnValue is somewhat inefficient, since it does a dictionary lookup twice. This isn't a big deal for a small dictionary, but for a larger one you will want to switch to TryGetValue.

Also, your assumption 3 holds - at least for now. But the Dictionary contract makes no guarantee that the Keys property always returns the same object. And since it's so easy to not rely on this, I'd recommend against it. Whenever I need an object to lock on, I just create an object for that sole purpose. Something like:

private static Object _lock = new Object();