Possible Duplicate:
Is there any reason to lock on something other than new object()?
I am wondering what is the best private static object to lock on, if indeed there is a difference.
At the moment, most of my code consits of :
private static object m_lockObject = new object();
lock(m_lockObject)
{
..critical thread code here
}
Instead of locking on just a object, should I use a different type? Like a custom class instance, an int, or a string, etc…? Or does it not matter?
Thanks
Lockstatement is just a syntactic sugar for underlyingMonitorobject. For the purpose of locking, it uses a reference. It doesn’t matter what reference it is – from the Monitor’s point of view! Locking onstringhowever may cause unexpected results due to strings being interned for example. And locking on value types would get you an exception because of boxing.TL;DR version – you’re doing it quite right (if the
staticpart is really your desired behaviour)