开发者

Problem with events and deadlocks

开发者 https://www.devze.com 2023-03-01 01:17 出处:网络
I have a problem raising events inside a lock. The event is fired inside a p开发者_高级运维roperty setter in a base class (when I change the property value), and i call this property in a derived cla

I have a problem raising events inside a lock.

The event is fired inside a p开发者_高级运维roperty setter in a base class (when I change the property value), and i call this property in a derived class (inside a lock).

The code looks something like this:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消