Problem with events and deadlocks
class BaseClass
{
public event EventHandler StatusChanged;
int _status = 0;
object lockA = new object();
public int Status
{
get
{
lock (lockA) { return _status; }
}
set
{
bool fireEvent = false;
lock (lockA)
{
if (_status != value)
{
_status = value;
fireEvent = true;
}
}
if (fireEvent)
StatusChanged(this, EventArgs.Empty);
}
}
}
class DerivedClass : BaseClass
{
object lockB = new object();
public void SetStatus(int newStatus)
{
lock (lockB)
{
this.Status = newStatus;
}
}
}
The BaseClass property raises the event outside the lock to protect itself from deadlocks, but the derived class sets the new status inside its own lock. Since the derived class' developer may not know how the base class works, what is the best way to ensure that a deadlock cannot happen? Maybe raising events in a asynch thread?
Lock in the same thread does not "lock", so there is not deadlock risk in my opinion with your code.
Well, I guess I'd have to agree that there really isn't a risk of deadlock there. But, what do you think about using BeginInvoke() to launch the user code?
BeginInvoke(this, EventArgs.Empty, null, null);
When you create the BaseClass just comment it as being ThreadSafe, then if any developers implement this base class and don't see that its comments state that it is already thread safe then it's their own problem.
I thought thier might be a attribute that states a class is threadsafe but there isn't one. Sorry.
精彩评论