2

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;
  }
}
Cat Zimmermann
  • 1,422
  • 2
  • 21
  • 38
  • "Probably with Expressions" : what makes you think that ? – Thomas Levesque May 04 '10 at 15:59
  • I may not be able to use the += and -= operators on a base EventHandler, so I might have to write the entire += and -= expressions as anonymous functions: RegistertEvent( ()=>SomeEvent+=SomeReaction, ()=>SomeEvent-=SomeReaction ) – Cat Zimmermann May 04 '10 at 19:47

2 Answers2

3

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
  • 5,955
  • 3
  • 31
  • 73
0

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.

sonnyb
  • 3,194
  • 2
  • 32
  • 42
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184