tags:

views:

146

answers:

3

Is it possible to do something like this in C#? Probably with Expressions. The EventHandlers are not members of a Control or any class that I own.

E.g.:

Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);

The EventHandler is a static reference that I don't own. How can I pass that type of statement to the following function?

private void RegisterEvent(EventHandler handler, Action<EventArgs> action)
{
   handler += action;
   m_toUnsubscribe.Add(handler, action);
}

... in Dispose()
{
  foreach(var pair in m_toUnsubscribe)
  {
    pair.handler -= pair.action;
  }
}
+3  A: 

Like described in the forum thread you can set the event to null in the dispose method of your object. Of course that requires your class to implement IDisposable.

Here the link: http://channel9.msdn.com/forums/TechOff/148255-Event-disposal/

Sebastian P.R. Gingter
I don't own the event, so I can't set it to null.
Cat
A: 

You can take a look at this post and use the answer I posted. The Suppress function will remove the handlers from a control. You could modify this more to suit your needs.

SwDevMan81
Actual URL: http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control/1597332#1597332
Cat
This is not a Control, and I don't own the events passed to RegisterEvent.
Cat
A: 

You could also use a WeakReference in between the object sending the event and the object receiving the event. When the object is no longer needed, it will be garbage collected normally, and the event will go away.

Neil Whitaker