Yet another threading/synchronization question

  • Thread starter Thread starter Jeff Johnson
  • Start date Start date
J

Jeff Johnson

With all the stuff I've read on threading I ought to know this, but I'm
going to ask anyway.

I have a class which can have multiple instances running one different
threads. Each instance may need to update a static dictionary in the same
class. Is the preferred way on synchronizing access to this dictionary to do
something like this:

private static Dictionary<string, string> _whateverDict = new
Dictionary<string, string>();
private static object _globalLockObject = new object();

private void SomeMethod()
{
lock (_globalLockObject)
{
// Access dictionary here
}
}
 
With all the stuff I've read on threading I ought to know this, but I'm
going to ask anyway.

I have a class which can have multiple instances running one different
threads.

Argh, "...running ON different threads."
 
Jeff Johnson wrote:

The code below is fine, but you could improve it by wrapping it all in a
static class. That class could be embedded in your original class. That
allows you to force all access to the Dictionary through a few public
static methods.

-hh-
 
Back
Top