How does making a locker object static affect its behavior?
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)
M开发者_如何转开发onitor.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 _locker
static 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 _locker
static.
In other words, it depends on what the real code for // Do something else
is.
The object will be shared between all instances, and so each object will block if they try to acquire the lock and any other object has it.
精彩评论