1
lbl1.BackColor = Color.Red;    //change backcolors of labels
lbl2.BackColor = Color.Red;
Thread.Sleep(2000);

lbl1.Text = val1.ToString(); //assign values to labels
lbl2.Text = val2.ToString();
Thread.Sleep(2000);

lbl1.BackColor = Color.Green; //reassign original backcolors
lbl2.BackColor = Color.Green;

This is a part of a method called inside a recursive method. I want to break down these steps to show a slow simulation. But, this doesn't gives the expected output.

Is there a better way? Please suggest.

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
jon_spades
  • 31
  • 5
  • 5
    You can't, because you're blocking the UI thread by sleeping it. If you block the UI thread, it can't render the changes to the UI. You need to learn how the UI thread works in forms applications first. Your favorite search engine will contain many relevant links. –  Aug 30 '16 at 13:06
  • Use a timer or a backgroundworker: http://stackoverflow.com/questions/34298057/moving-a-picture-box-gradually-not-instantly/34566523#34566523 – rene Aug 30 '16 at 13:10
  • Will is right, perhaps get some inspiration from this: http://stackoverflow.com/questions/13206926/vb-net-progressbar-backgroundworker – Jeremy Thompson Aug 30 '16 at 13:11
  • don't use `Thread.Sleep` as @Will said already...you can use `async` to make it more simple.. – Raktim Biswas Aug 30 '16 at 13:13

1 Answers1

4

Don't use Thread.Sleep() as it freezes the UI, rather you can do the same work by implementing your own Asynchronous method.

You can also achieve the same by using Timers.

This is an example on how to manage tasks asynchronously. Suppose, this is my method Perform()

private async Task Perform()
{
    lbl1.BackColor = Color.Red;    
    lbl2.BackColor = Color.Red;
    await Task.Delay(2000);

    lbl1.Text = val1.ToString();  
    lbl2.Text = val2.ToString();
    await Task.Delay(2000);

    lbl1.BackColor = Color.LightSeaGreen;  //changed to lightseagreen as the green you used
    lbl2.BackColor = Color.LightSeaGreen;  //was hurting my eyes :P
}

and I call it in an event say, on a button_click event.

private void button1_Click(object sender, EventArgs e)
{
    Task t = Perform();
}

                                                       The output will be like:

                                                      async click


Learn more on how to use async and await.

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32