Unregister events with a new delegate instance

EventHandler a = new EventHandler(control_RegionChanged);
EventHandler b = new EventHandler(control_RegionChanged);

 if (a == b)
 {
     Console.WriteLine("Same!");
 }
 else
 {
     Console.WriteLine(a.GetHashCode() + " " + b.GetHashCode());
 }

This writes Same!to the console.

control.RegionChanged += new EventHandler(control_RegionChanged);
control.RegionChanged -= new EventHandler(control_RegionChanged);

After executing this code is EventHandlerunregistered?

+3
source share
2 answers

Yes; delegates are compared by instance and MethodInfo; if they match then it will work. The problem occurs when you try to abandon the anonymous method; in this case, you must leave a link to the delegate to unsubscribe.

So:

This is normal:

control.SomeEvent += obj.SomeMethod;
//...
control.SomeEvent -= obj.SomeMethod;

But this is much riskier:

control.SomeEvent += delegate {Trace.WriteLine("Foo");};
//...
control.SomeEvent -= delegate {Trace.WriteLine("Foo");};

The correct process with anonymous methods:

EventHandler handler = delegate {Trace.WriteLine("Foo");};
control.SomeEvent += handler;
//...
control.SomeEvent -= handler;
+7
source

Try using

control.RegionChanged += control_RegionChanged
control.RegionChanged -= control_RegionChanged

This should also work (from memory - did not check it). At the very least, it does not create a new event handler link.

0
source

All Articles