Fast and continuous exchange of the background color of a Panel

1

I'm trying to make a panel constantly change color with the following code

while (true)
{
   panelColor.BackColor = Color.Blue;
   Thread.Sleep(500);
   panelColor.BackColor = Color.Red;
   Thread.Sleep(500);
}

The problem is that the application crashes every time it arrives in this part, can someone tell me why?

    
asked by anonymous 04.10.2016 / 15:46

1 answer

2

The application hangs because it is running an loop infinity.

You also do not see the background changing color for the same reason, as UIThread is blocked from running this code, the windows framework has no opportunity to redraw the controls.

Change the code as follows:

while (true)
{
   panelColor.BackColor = Color.Blue;
   panelColor.Refresh();
   Thread.Sleep(500);

   panelColor.BackColor = Color.Red;
   panelColor.Refresh();
   Thread.Sleep(500);
}

The method refresh () makes auto control redraw itself.

    
04.10.2016 / 16:13