I have a simple form with a splitviewcontainer on it, the left hand side is a menu, and the right hand side contains one or more controls.
One of the controls which can be loaded on the RHS contains a timer to refresh its data every few seconds.
If I use Controls.Clear() on the right hand side, the control is no longer displayed, but I assume it hasn’t been disposed since the timer is still firing (I can see the database calls being made in logs).
My question is thus, how should I clean up my control when it has been removed from being displayed? Which event/method is called when the control is cleared?
You should call the appropriate
Dispose()method on the controls.You can use an extension method to do this, see this answer from Hans Passant.
Now, you may have a race condition here. The timer could be due for a callback when you call your yet-to-be-created
Clear()extension method. If your timer callback function is going to potentially lead to data corruption in your application, you will have to do something like this.Now the other question is – Is it possible for you to just hide these controls? Is there a constraint that is preventing you from doing that?