I have a list of objects and I would like to subscribe/unsubscribe each of them to an event (via a delegate because I need to pass extra params to the methods). So I have something like this:
public void MonitoringCtrl(bool monitoringOn)
{
foreach (var mh in monHandlers)
{
evHandler = (sender, e) => OnNotification(sender, e, mh);
if (monitoringOn)
{
//subscribe to event
mh.monitoredItem.Notification += evHandler;
}
else
{
//unsubscribe
mh.monitoredItem.Notification -= evHandler;
}
}
//do other stuff
}
This works when subscribing, but doesn't work when unsubscribing, presumably because I re-declare the evHandler inside the foreach. How can I save the reference to the evHandler?