0

I have a method that accepts a string parameter, and the method will be called concurrently. I want to lock between calls that pass in the same string. For example, two threads pass in "abc" to call the method at the same time, then I hope they one by one. At the same time, the call to "xyz" from another thread is not affected. So what should I lock?

void Foo(string s) {
   lock(what) {} // ???
}

I am currently locking String.Intern(s), but I understand that this will increase the uncollectable interned string, and this method will be called countless times by passing countless different strings during the app running, so I want to improve it.

ahdung
  • 350
  • 3
  • 13
  • Check out the answer here for code that will lock on a specific value https://stackoverflow.com/a/31194647/302918 – juharr Dec 11 '20 at 03:35
  • 1
    @Enigmativity I think that [this](https://stackoverflow.com/questions/33786579/how-to-dynamically-lock-strings-but-remove-the-lock-objects-from-memory "How to dynamically lock strings but remove the lock objects from memory") question is a more suitable duplicate (than [this](https://stackoverflow.com/questions/31138179/asynchronous-locking-based-on-a-key)), because it explicitly asks for removing unused locks from memory, and it refers to synchronous locking. Using asynchronous lockers synchronously adds overhead, without offering anything in return. – Theodor Zoulias Dec 11 '20 at 10:26

0 Answers0