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.
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.