jon_spades jon_spades - 3 months ago 15
C# Question

Show a slow simulation using Thread.Sleep()

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;


I'm new to c# ..this is a part of a method called inside a recursive method..i want to break down these steps show a slow simulation.but this doesnt give expected output... Is there a better way!! please suggest...

Answer

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.

Comments