0

I need to create a script such as chronometer.

I write a code like following;

for(int i=0;i<50;i++)
{
    textBox.Text = i.Tostring();
    Task.Delay(100).Wait();
}

The expected output is like a chronometer ; an increasing text by 1 up to 49 started from 0 at textbox.

But I get only 49 after a 49*100 miliseconds pause later.

How can I solve this ?

2
  • You need to await Task.Delay(100); Commented Aug 27, 2016 at 8:34
  • 1
    If you can live with blocking the UI thread you could insert a textBox.Refresh();. BUT: You really shouldn't. So using a Timer is the regular solution; but the acepted answer is also correct. Commented Aug 27, 2016 at 11:01

1 Answer 1

2

The event or method running this piece of code needs to be asynchronous. This is in order for the UI to be responsive:

private async void btnDoWork_Click(object sender, EventArgs e)
{
    for(int i=0;i<50;i++)
    {
        textBox.Text = i.Tostring();
        await Task.Delay(100);
    }
}

Otherwise, you'll be blocking the UI Thread and you will not be able to see the Text Box changing. You'll only see the last change which is 49 in your case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.