Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking on string-key

Tags:

c#

locking

How do I perform a lock based on a specific string-key?

public void PerformUpdate(string key)
{
    // TODO: Refine this, since they key-string won't 
    // be the same instance between calls

    lock(key)
    {
        PerformUpdateImpl()
    }
}

I've tried to keep lock-objects in a ConcurrentDictionary, but somehow this doesn't hold up either.

like image 490
Seb Nilsson Avatar asked Dec 21 '22 13:12

Seb Nilsson


1 Answers

Although this isn't concurrent (you can make it so), what about Dictionary<string,object>.

Wouldn't this work?

dict.Add("somekey",new object());

lock (dict["somekey"]) {
  ...
}

This would allow a thread to lock a named instance of an object, which would I think do what you want.

like image 191
Lloyd Avatar answered Dec 29 '22 00:12

Lloyd