Avoid duplicate event subscriptions in C#

前端 未结 5 1986
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-25 15:28

How would you suggest the best way of avoiding duplicate event subscriptions? if this line of code executes in two places, the event will get ran twice. I\'m trying to avoid

5条回答
  •  星月不相逢
    2020-12-25 15:44

    I think, the most efficient way, is to make your event a property and add concurrency locks to it as in this Example:

    private EventHandler _theEvent;
    private object _eventLock = new object();
    public event EventHandler TheEvent
    {
        add
        {
            lock (_eventLock) 
            { 
                _theEvent -= value; 
                _theEvent += value; 
            }
        }
        remove
        {
            lock (_eventLock) 
            { 
               _theEvent -= value; 
            }
        }
    }
    

提交回复
热议问题