How to ensure an event is only subscribed to once

前端 未结 7 1714
南旧
南旧 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:52

    I know this is an old Question, but the current Answers didn't work for me.

    Looking at C# pattern to prevent an event handler hooked twice (labelled as a duplicate of this question), gives Answers that are closer, but still didn't work, possibly because of multi-threading causing the new event object to be different or maybe because I was using a custom event class. I ended up with a similar solution to the accepted Answer to the above Question.

    private EventHandler<bar> foo;
    public event EventHandler<bar> Foo
    {
        add
        {
            if (foo == null || 
                !foo.GetInvocationList().Select(il => il.Method).Contains(value.Method))
            {
                foo += value;
            }
        }
    
        remove
        {
            if (foo != null)
            {
                EventHandler<bar> eventMethod = (EventHandler<bar>)foo .GetInvocationList().FirstOrDefault(il => il.Method == value.Method);
    
                if (eventMethod != null)
                {
                    foo -= eventMethod;
                }
            }
        }
    }
    

    With this, you'll also have to fire your event with foo.Invoke(...) instead of Foo.Invoke(...). You'll also need to include System.Linq, if you aren't already using it.

    This solution isn't exactly pretty, but it works.

    0 讨论(0)
提交回复
热议问题