Ok, I'd like people's opinions on the use of the lock() keywork in C#. I've never quite got the subtleties of threading (no CS degree!).
The scenario is that I have a class that contains a Dictionary<string, object> that is referenced by several other classes. I'd like to make assess to that dictionary thread safe.
The 'standard' way to do this is to use a separate lock object
class MyClass
{
Dictionary<string, object> _store = new Dictionary<string, object>();
object _lock = new object();
public void Add(string key, object value)
{
lock(_lock)
{
_store.Add(key, value);
}
}
}
It has occurred to me, that perhaps I should lock the target object itself, thus doing away with the added lock object:
class MyClass
{
Dictionary<string, object> _store = new Dictionary<string, object>();
public void Add(string key, object value)
{
lock(_store)
{
_store.Add(key, value);
}
}
}
Is this safe?
Herbie
EDIT: Why does the code formatting suck? Where do these double-spaced lines come from?