I subscribe to an event like this:
private void CoupleOverlay(IMapVisual mapVisual)
{
overlay.DrawTilesProgressChanged += (s, e) =>
{
mapVisual.DrawingProgress = e.ProgressPercentage;
};
}
The application may call CoupleOverlay event many times so I need to unsubscribe DrawTilesProgressChanged event and subscribe again but because it is an anonymous event I can’t unsubscribe from it. I tried to convert to
private void CoupleOverlay(IMapVisual mapVisual)
{
overlay.DrawTilesProgressChanged -=overlay_DrawTilesProgressChanged;
overlay.DrawTilesProgressChanged +=overlay_DrawTilesProgressChanged;
}
private void overlay_DrawTilesProgressChanged(object sender, DrawTilesProgressChangedTileOverlayEventArgs e)
{
mapVisual.DrawingProgress = e.ProgressPercentage;
}
It is not working because mapVisual is not valid variable on overlay_DrawTilesProgressChanged method.
If I change the code to
private void CoupleOverlay(IMapVisual mapVisual)
{
EventHandler<DrawTilesProgressChangedTileOverlayEventArgs> drawEvent = (s, e) =>
{
mapVisual.DrawingProgress = e.ProgressPercentage;
};
overlay.DrawTilesProgressChanged -= drawEvent;
overlay.DrawTilesProgressChanged += drawEvent;
}
It will not work cause drawEvent is a local variable and next time I call CoupleOverlay, it will create new one.
So How can I unsubscribe from this event handler? Or how can I know I’m subscribed to the event so I don’t need to subscribe again?
Indeed. You’d basically need to keep an instance variable instead of a local variable. The instance variable would effectively be “the currently subscribed event handler”. Then in
CoupleOverlayyou’d remove that event handler, create a new one (storing it in the variable) and resubscribing with it.An alternative would be to use a single event handler, but keep the “current” overlay and map visual as instance variables, used by the event handler. The
CoupleOverlaymethod would then just need to update those variables.