Alex
Alex

Reputation: 21

How do I change a property of a control several times during a loop in C#

I'm trying to do something like this:

int i;
while(true)
{
    label1.Text = i.ToString();
    i++;
    Thread.Sleep(500);
}

(in reality I'm trying to do something more complex and that makes more sense but this is a simple example of my problem) I'm expecting that the text of the lable changes each 1/2 seconds..but it is getting stuck.

Thanks you

Upvotes: 2

Views: 105

Answers (6)

Gilad Naaman
Gilad Naaman

Reputation: 6550

You can't make the GUI-Thread sleep (Because than the GUI wont respond) (And I'm saying that even though I like sleeping * A LOT *).

Consider one of the following alternatives:

  • Running this code on a separate thread
  • Creating a timer with 500 as an interval
  • Some sort of binding

Upvotes: 5

takteek
takteek

Reputation: 7110

The way you have it now, your code is running on the same thread as the GUI. After you set the new label text you immediately sleep which prevents any code responsible for actually updating the screen from running. You can put Application.DoEvents() before your sleep call to force it to process any messages but that's not a real solution.

What you need to do is put your time-consuming code on a different thread. The .NET Timer class is made for something simple like this. You could also make your own separate thread containing your loop code. Just make sure you only access the label from the same thread it was created on. You can accomplish that by passing a delegate to label1.Invoke that does the actual text updating.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160862

Use a background thread or a timer, otherwise you will block the UI:

Thread t = new Thread( () =>
{
    int i = 0;
    while (true)
    {
        label1.Invoke( new Action(() => { label1.Text = i.ToString();}));
        i++;
        Thread.Sleep(500);
    };   
});
t.IsBackground = true;
t.Start();

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062725

Sleeping the UI thread makes things worse, as it can't respond to "paint" events until it has finished your method.

The most appropriate option here is a timer, doing a bit of work on each tick.

A lazy and deeply flawed approach is to add Application.DoEvents() - I only mention this to allow me to say DON'T DO THIS!!!

Upvotes: 3

Kon
Kon

Reputation: 27441

You will never get out of the while loop, thus the stuck part. Also, if this is a WinForm, you need to repaint/invalidate/refresh your UI to see anything update. More info on that here: C#: How do I repaint my form when it's not focused?

Upvotes: -1

james_bond
james_bond

Reputation: 6908

There is no break condition on your loop

maybe you're trying to do, see that Update is called to repaint the label.

int i; 
for (i=0; i!=10; i++){ 
        label1.Text = i.ToString();
        label1.Update();
        Thread.Sleep(500); 
}

Upvotes: -1

Related Questions