3

I am just curious if it possible to use const value as lock, for example:

private const string counterKey = "Requests_Sec";
public static object RequestsPerSecond()
{
   lock (counterKey)
   {
       // do something...
   }
}

I presumed const is static so I used it in this situation; and am curious if reverting to static string is what solved the problem.

EDIT: Most of you are saying that string is the problem rather than const. To rephrase my question - would this be OK for locking:

private const object counterKey = new object();

EDIT: My bad - you can't have const object... what I take away from this is always lock on object _sync = new object(); and make it static if needed.

2
  • 1
    a const object can only have the value null. and even if you could declare it as an object, it would still be an instance of the string in the intern pool, so the problem would be the same.
    – phoog
    Nov 25, 2011 at 5:54
  • related: stackoverflow.com/q/6937342/158779 Nov 26, 2011 at 2:45

3 Answers 3

4

This about locking on string rather then locking on a static const. There are only 2 types of variables that can be marked const and those are primitive value types and strings. On the first one you can't lock. Note that due to string intering, making the string const or not wont likely make much difference in regards to the instance of the string.

For an answer on the question how locking on strings work, see: Using string as a lock to do thread synchronization

Basically, it's not safe to lock on a string.

1
  • 3
    reference types can be const, too, as long as the value is null. of course, you can't lock on null.
    – phoog
    Nov 25, 2011 at 6:00
3

The answer is probably: yes, the lock works. But I have to say: No, don't do this. Even it works, it confuses others. Use a normal object lock is much better.

1

the const part is throwing you off the main issue.

any string is mapped to a single representation of it in memory.... as in "a" declared in one place is the same as "a" declared elsewhere. Ergo, in most cases, locking simply on a string will cause a monitor to wait anywhere that uses the same string. It's like a Mutex lock for the same process.

so it's important to note that you're not locking on that reference to that string, you're locking on all references to that string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.