How to change TextBlock.Text every loop?

Viewed 110

This is UWP C# application. I want to display the i variable.

    private void btn2_Click(object sender, RoutedEventArgs e)
    {
        for(int i = 0; i<=10000000; i++)
        {
            textBlock2.Text = i.ToString();
        }
    }

But after I clicked the button, the text only change one time after the loop is finished.
How can see changing text in every loop?

1 Answers

Actually, your UI is frozen while the long loop is executing, so nothing can be updated on the screen. Try this

private async void btn2_Click(object sender, RoutedEventArgs e)
{
    for(int i = 0; i<=10000000; i++)
    {
        textBlock2.Text = i.ToString();
        await Task.Delay(200); //stay 200 ms before showing next number so human eyes can see it.
    }
}

When it executes to this line await Task.Delay(200);, the loop is temporarily suspended - for 200 milliseconds, and the UI thread now has a chance to process the drawing tasks pending in the queue, which includes redrawing the textblock.

Related