0

I have 4 labels, that must change to bold after waiting 500ms each.

I've tried to use this function:

       LabelUpdater(lblIF); //to bold
       Thread.Sleep(500);
       LabelUpdater(lblIF); //to regular again
       LabelUpdater(lblID); //to bold
       Thread.Sleep(500);
       LabelUpdater(lblID); //to regular again


    private void LabelUpdater(Label labelActual)
    {
        if (labelActual.Font.Bold)
        {
            Console.WriteLine("Regular - " + DateTime.Now);
            labelActual.Font = new Font(labelActual.Font, FontStyle.Regular);
        }
        else
        {
            Console.WriteLine("Bold- " + DateTime.Now);
            labelActual.Font = new Font(labelActual.Font, FontStyle.Bold);
        }
    }

But if I try to run this program, nothing changes. If I just set to bold, everything turn bold in the end of execution.


To get working, i needed to use this:

       LabelUpdater(lblIF); 
       Thread.Sleep(500);
       Application.DoEvents(); //here
       LabelUpdater(lblIF); 
       LabelUpdater(lblID); 
       Thread.Sleep(500);
       Application.DoEvents(); //here
       LabelUpdater(lblID); 

Not sure why, i just tried and worked! :D

Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79

2 Answers2

3

you could use Timer Control instead of using Thread.Sleep() as it blocks the main UI.

Step1: Add Timer Control to your Windows Form.

Step2: Set the Interval property of Timer control to 500(Ex:1000 milliseconds = 1 sec)

Step4: Set the Enabled Property to True

Step5: Handle the Tick Event of Timer control as below:

private void timer1_Tick(object sender, EventArgs e)
        {
          LabelUpdater(lblIF); //to bold
        }
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
1

It sounds like your code is running on the main GUI thread, is it in a button click handler?

The events that you fire in your code are not processed until the current handler has finished executing.

Try running your code on a background thread or, in resposne to a timer. Note that you'll need to handle cross-thread calls to the GUI.

Task.StartNew(BackgroundLabelToggle, Label[] {  lblIF, lblID });

private static void BackgroundLabelToggle(Label[] labels)
{
   var a = labels[0];
   var b = labels[1];

   a.Invoke(LabelUpdater, a); //to bold
   Thread.Sleep(500);
   a.Invoke(LabelUpdater, a); //to regular again
   b.Invoke(LabelUpdater, b); //to bold
   Thread.Sleep(500);
   b.Invoke(LabelUpdater, b); //to regular again
}
Jodrell
  • 34,946
  • 5
  • 87
  • 124