How to ensure an event is only subscribed to once

前端 未结 7 1757
南旧
南旧 2020-11-27 04:20

I would like to ensure that I only subscribe once in a particular class for an event on an instance.

For example I would like to be able to do the following:

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 04:31

    U can use Postsharper to write one attribute just once and use it on normal Events. Reuse the code. Code sample is given below.

    [Serializable]
    public class PreventEventHookedTwiceAttribute: EventInterceptionAspect
    {
        private readonly object _lockObject = new object();
        readonly List _delegates = new List();
    
        public override void OnAddHandler(EventInterceptionArgs args)
        {
            lock(_lockObject)
            {
                if(!_delegates.Contains(args.Handler))
                {
                    _delegates.Add(args.Handler);
                    args.ProceedAddHandler();
                }
            }
        }
    
        public override void OnRemoveHandler(EventInterceptionArgs args)
        {
            lock(_lockObject)
            {
                if(_delegates.Contains(args.Handler))
                {
                    _delegates.Remove(args.Handler);
                    args.ProceedRemoveHandler();
                }
            }
        }
    }
    

    Just use it like this.

    [PreventEventHookedTwice]
    public static event Action GoodEvent;
    

    For details look at Implement Postsharp EventInterceptionAspect to prevent an event Handler hooked twice

提交回复
热议问题