Click here to Skip to main content
13,550,448 members
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 30 Jan 2008
Licenced BSD

A basic named lock class

, 30 Jan 2008
Rate this:
Please Sign up or sign in to vote.
This is a utility class for acquiring named locks.


There are a few problems I've come across where synchronizing a particular "name" might be useful. One of the apps I work on makes heavy use of Lucene.NET; each page shows the results of a couple of queries. It doesn't make a whole ton of sense to run multiple, identical queries against Lucene at the same time, so I generate a key for each query, lock against that key, and let the first thread do the actual work while the others sit around sipping coffee.

Using the code

It's pretty simple to use this class. Create a new instance of NamedLock<string>, then call the Lock function within a using statement.

NamedLock<string> locker = new NamedLock<string>();
var url = "";
using (locker.Lock(url))
    //Do something synchronized
    var xml = new XmlDocument();

Points of interest

Have a look at the class itself. It's relatively small, and consists of three things:

  • The primary class with the Lock and Unlock functions
  • An internal Token class that implements IDisposable
  • An internal ReferenceCount class

NamedLock<t /> is pretty simple. It contains a Dictionary<T, ReferenceCount> to keep track of which names are currently locked, and provides utility functions for acquiring and releasing locks. Lock looks like this:

public IDisposable Lock(T name, int timeout)
    ReferenceCount obj = null;
    lockCollection.TryGetValue(name, out obj);
    if (obj == null)
        obj = new ReferenceCount();
        lockCollection.Add(name, obj);
        if (!Monitor.TryEnter(obj, timeout))
            throw new TimeoutException(
                "Timeout while waiting for lock on {0}", 

    return new Token<T>(this, name);

This function locks the lockCollection, checks for an existing lock with the same name, adds one if it's the first, then locks and returns a token. There's a good reason it uses Monitor.Enter instead of a simple lock statement: you'll notice that if there's no current lock in the collection, we actually lock the sync object (named obj) before releasing the lock on the collection. If the lock does exist in the collection, we increment a reference counter, release the collection lock, and then lock on the sync object. Doing it this way lets us avoid deadlocks on the lock collection (bad juju).

The Unlock function is also straightforward:

public void Unlock(T name)
    lock (lockCollection)
        ReferenceCount obj = null;
        lockCollection.TryGetValue(name, out obj);
        if (obj != null)
            if (0 == obj.Release())

It locks the lockCollection, grabs the sync object, releases the named lock, then removes the sync object if there aren't any other threads holding references to it. This code is a bit more straightforward, since we don't have to do anything janky to avoid dead locks on the lock collection.

The token class is so shockingly simple I'm not even going to paste it here. It takes a reference to the parent NamedLock, and then calls parent.Unlock(name) when disposed.



This article, along with any associated source code and files, is licensed under The BSD License


About the Author

Kurt Mackey
CEO Mubble Inc
United States United States
I'm currently running a software company that sells a publishing system for ad-driven content sites. The largest site using the system at the moment is Ars Technica.

You may also be interested in...

Comments and Discussions

QuestionAwesome! Pin
Nov.Ice14-Jun-14 3:01
memberNov.Ice14-Jun-14 3:01 
GeneralNamed Reader Writer Lock Pin
zcrar7015-Nov-09 9:21
memberzcrar7015-Nov-09 9:21 
Similar to the named lock in the article, I wrote a named reader-writer lock class based on the .Net framework's ReaderWriterLockSlim class (rather than the Monitor used above.)

I posted the code here in case anyone finds it useful: named reader writer lock in C#

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01-2016 | 2.8.180515.1 | Last Updated 30 Jan 2008
Article Copyright 2008 by Kurt Mackey
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid