How do I turn off timers in my controls after clearing them?

I have a simple form with a dividing connector on it, the left side is a menu, and the right side contains one or more controls.

One of the controls that can be loaded into the RHS contains a timer to update its data every few seconds.

If I use Controls.Clear () on the right side, the control no longer appears, but I assume that it has not been deleted since the timer is still starting (I see that database calls are being made in the logs).

My question is, therefore, how should I clear my control when it was removed from the display? What event / method is called when the control is cleared?

+4
source share
3 answers

You must call the appropriate Dispose() method for the controls.

You can use the extension method for this, see this answer from Hans Passant.

One of the controls that can be loaded into the RHS contains a timer to update its data every few seconds.

You may now have a race condition. The timer can be called by a callback when you call the Clear() extension method that has not yet been created. If the timer callback function could potentially lead to data corruption in your application, you will need to do something like this.

 Timer.Stop(); Timer.Tick -= Timer_Tick(TimerCallback); Timer.Dispose(); 

Now another question: is it possible for you to hide these controls? Is there a restriction that prevents you from doing this?

+1
source

This piece of code should work

 public Form1() { InitializeComponent(); UserControl cc = new UserControl(); Panel pp = new Panel(); pp.Controls.Add(cc); pp.ControlRemoved += new ControlEventHandler(pp_ControlRemoved); pp.Controls.Clear(); } void pp_ControlRemoved(object sender, ControlEventArgs e) { var control = sender as MyVerySpecialControl; if (control != null) { //stop timers or unassign events } } 

I would be happy to answer any doubts.

+1
source

I would use the extension method, not Clear (). And swipe through the child controls and dispose of them specifically. If there are certaion controls that do not have IDispose (but should have) that call this, then you can catch them specifically in a loop and call any method to stop them before destroying them with the final clear.

0
source

Source: https://habr.com/ru/post/1401841/


All Articles