0

Recently I came across code as following:

void CallThisInDifferentThreads(Return return)
{
 var lock =  "lock";
 lock(lock)
    {
        //Do something here.
    }
}

My first reaction was that the lock in this code won't work because we are creating the lock and using it in the same method. Every Thread calling this method has it's own copy of lock so there will be no synchronisation.

But later I realized that this should work because string goes to string pool and there is only one instance of a particular string. I'm not sure If I'm correct.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
naveen
  • 1,016
  • 1
  • 9
  • 22

1 Answers1

5

Locking on strings is super bad. Don't do it. You have no guarantee that some other clever soul will not also lock on strings, and because they are effectively "super" global because of string interning, the moment this becomes accepted practice, the wheels will fall off.

Lock with a private object that has only one purpose... locking. Strings don't fit this description.

Locking by string. Is this safe/sane?

Is it OK to use a string as a lock object?

Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351