Let’s say I have a class with a member that looks like this:
readonly object _locker;
which I use to synchronize blocks of code like this:
lock (_locker)
{
// Do something
Monitor.Pulse(_locker);
}
and this:
lock (_locker)
{
while (someCondition)
Monitor.Wait(_locker);
// Do something else
}
Let’s say that I have multiple instances of this particular class, all running at the same time, using separate threads.
What happens to the behavior of the locks and the Monitor.Wait and Monitor.Pulse calls if I make the locker object static?
static readonly object _locker;
Do they all suddenly start working in lockstep (e.g. locking a block of code takes a lock across all instances of the object), or is there no change in behavior?
By making the
_lockerstatic you create 1 shared critical region. Yes, they will all wait for each other. That is sensible and necessary when your shared data is also static.If the shared data is per-instance, then don’t make the
_lockerstatic.In other words, it depends on what the real code for
// Do something elseis.