Reputation: 3395
I have a user control that is listening to an event.
public partial class ObserverControl : UserControl
{
public ObserverControl()
{
InitializeComponents();
Observatory.DataUpdated += OnDataUpdate;
}
private void OnDataUpdated(object sender, EventArgs e)
{
// Process new data
}
}
What is the best way to ensure that when this UserControl is closed, it unsubscribes from the event? Currently, it closes the Observatory class is still trying to send updates to the ObserverControl.
I have considered using IDisposable, but I'm not exactly sure how it would work (especially since the Dispose(bool disposing)
method is already overridden in the designer code).
Upvotes: 2
Views: 667
Reputation: 9389
Move the dispose method out of the generated file and add
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
Observatory.DataUpdated -= OnDataUpdate;
}
Upvotes: 2