views:

3904

answers:

7

Duplicate of: How to ensure an event is only subscribed to once and Has an event handler already been added?

I have a singleton that provides some service and my classes hook into some events on it, sometimes a class is hooking twice to the event and then gets called twice. I'm looking for a classical way to prevent this from happening. somehow I need to check if I've already hooked to this event...

+8  A: 

You need to implement the add and remove accessors on the event, and then check the target list of the delegate, or store the targets in a list.

In the add method, you can use the Delegate.GetInvocationList method to obtain a list of the targets already added to the delegate.

Since delegates are defined to compare equal if they're linked to the same method on the same target object, you could probably run through that list and compare, and if you find none that compares equal, you add the new one.

Here's sample code, compile as console application:

using System;
using System.Linq;

namespace DemoApp
{
    public class TestClass
    {
        private EventHandler _Test;

        public event EventHandler Test
        {
            add
            {
                if (_Test == null || !_Test.GetInvocationList().Contains(value))
                    _Test += value;
            }

            remove
            {
                _Test -= value;
            }
        }

        public void OnTest()
        {
            if (_Test != null)
                _Test(this, EventArgs.Empty);
        }
    }

    class Program
    {
        static void Main()
        {
            TestClass tc = new TestClass();
            tc.Test += tc_Test;
            tc.Test += tc_Test;
            tc.OnTest();
            Console.In.ReadLine();
        }

        static void tc_Test(object sender, EventArgs e)
        {
            Console.Out.WriteLine("tc_Test called");
        }
    }
}

Output:

tc_Test called

(ie. only once)

Lasse V. Karlsen
This code does not compile because 'Contains' is a private method.
Hermann
Please ignore my comment, I forgot the Linq using.
Hermann
A: 

have your singleton object check it's list of who it notifies and only call once if duplicated. Alternatively if possible reject event attachment request.

Toby Allen
+12  A: 

Explicitly implement the event and check the invocation list. You'll also need to check for null:

private EventHandler foo;
public event EventHandler Foo
{
    add
    {
        if (foo == null || !foo.GetInvocationList().Contains(value))
        {
            foo += value;
        }
    }
    remove
    {
        foo -= value;
    }
}

Using the code above, if a caller subscribes to the event multiple times, it will simply be ignored.

Judah Himango
This code does not compile because 'Contains' is a private method.
Hermann
You need to use the System.Linq using.
Hermann
Just to clarify Hermann's comment; you have to include the namespace 'System.Linq' by adding 'using System.Linq' to your class or current namespace.
Kjetil Klaussen
+2  A: 

You really should handle this at the sink level and not the source level. As the developer of a service, who are you to say that sinks can only register once? What if they want to register twice for some reason? And if you are trying to correct bugs in the sinks by modifying the source, it's again a good reason for correcting these issues at the sink-level. I'm sure you have your reasons, but perhaps you should consider an alternate architecture that leaves the semantics of an event in tact.

JP Alioto
+2  A: 

How about just removing the event first with '-=' , if it is not found an exeception is not thrown

/// -= Removes the event if it has been already added, this prevents multiple firing of the event ((System.Windows.Forms.WebBrowser)sender).Document.Click -= new System.Windows.Forms.HtmlElementEventHandler(testii); ((System.Windows.Forms.WebBrowser)sender).Document.Click += new System.Windows.Forms.HtmlElementEventHandler(testii);

PrimeTSS
A: 

Microsoft's Reactive Extensions (Rx) framework can also be used to do "subscribe only once".

Given a mouse event foo.Clicked, here's how to subscribe and receive only a single invocation:

Observable.FromEvent<MouseEventArgs>(foo, "Clicked")
    .Take(1)
    .Subscribe(MyHandler);

...

private void MyHandler(IEvent<MouseEventArgs> eventInfo)
{
   // This will be called just once!
   var sender = eventInfo.Sender;
   var args = eventInfo.EventArgs;
}

In addition to providing "subscribe once" functionality, the RX approach offers the ability to compose events together or filter events. It's quite nifty.

Judah Himango