Questions:
- Can I deadlock this code? Does the IsMouseInside property is thread safe?
- Does the use of the copy variable make sense?
PS: UI thread updates IsMouseInside. Another thread will read its value some times
public Class Test
{
private readonly object isMouseInsideLocker = new object();
private bool isMouseInside =开发者_如何学Python false;
public bool IsMouseInside
{
get
{
bool copy;
lock (this.isMouseInsideLocker)
copy = this.isMouseInside;
return copy;
}
set
{
lock (this.isMouseInsideLocker)
this.isMouseInside = value;
}
}
private void lblProcessTime_MouseEnter(object sender, EventArgs e)
{
IsMouseInside = true;
}
private void lblProcessTime_MouseLeave(object sender, EventArgs e)
{
IsMouseInside = false;
}
}
- No, you can't.
- It doesn't. Just
return isMouseInside;
No that can't deadlock; there is only one lock object, and no extension point exists that would allow you to do something messy while the lock is held. However, if you are using lock you should probably make it clear what scenarios you are trying to avoid. While the meaning is actually very subtle, I wonder whether volatile
might work here without needing any locks. Or Interlocked
on an int
that is always either 0
or 1
.
But sure, it looks like it'll work; bool is always atomic anyway, so the lock here is only really acting as a memory-barrier avoiding cache issues (hence why volatile might also work). And remember that any time you get the value, that is now stale and might already be incorrect. It was true at the point of read, though.
- You can't deadlock - you are locking on the same object.
- It doesn't make sense to me. Also the locking doesn't make sense - I don't think you achieve anything with it.
What is the goal?
You can only have a deadlock if you have two different locks A and B that two different threads try to acquire in different order - since you only have one lock here you are safe.
Also keep in mind that C# lock (which is syntactic sugar for using a Monitor) is reentrant - a single thread cannot deadlock since it can reenter a lock as many times as it wants to once it has initially acquired it.
精彩评论