String key lock

How to 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 tried to save the blocking objects in ConcurrentDictionary , but somehow this also does not linger.

+4
source share
2 answers

Although this is not the same (you can do it this way), how about Dictionary<string,object> .

Does this work?

 dict.Add("somekey",new object()); lock (dict["somekey"]) { ... } 

This will allow the thread to block the named instance of the object, which I think will do what you want.

+9
source

One way to do something like this is to create a Dictionary<string,object> and use this to go from the string to the object that I am blocking. You may need to provide access to this dictionary in streaming mode (for example, locking around it), and if you need to block between different instances, make it static, etc. But this is a wide technique that I used for this.

+2
source

Source: https://habr.com/ru/post/1445041/


All Articles