Label does not change value inside while loop

private void button1_Click(object sender, RoutedEventArgs e)
{
        int i = 0;

        while (i < 500)
        {
            label1.Content = i.ToString();
        //  System.Threading.Thread.Sleep(2000);
            ++i;
        }
 }

I try to update the contents of the label every time the variable is incremented, but the label1 event occurs. The content changes only once and only after the while loop completes. I thought the increment of the counter variable was so fast that the user interface thread could not catch up with it, so I wanted the thread to stand idle for 2 seconds, hoping to see the value of label1 500 times. That didn't work either. Why?

+5
source share
5 answers

As others have said, the problem is that you are blocking the user interface thread.

, Application.DoEvents, DispatcherTimer . :

DispatcherTimer timer = new DispatcherTimer();
timer.Tick += delegate
{
    label.Content = counter.ToString();
    counter++;
    if (counter == 500)
    {
        timer.Stop();
    }
};
timer.Interval = TimeSpan.FromMilliseconds(2000);
timer.Start();

( , Application.DoEvents WPF, . , , . .)

Timer ( System.Threading.Timer, System.Timers.Timer), . DispatcherTimer - Tick Dispatcher.

EDIT: DoEvents, , , MSDN docs Dispatcher.PushFrame, , Application.DoEvents, WPF:

public void DoEvents()
{
    DispatcherFrame frame = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
        new DispatcherOperationCallback(ExitFrames), frame);
    Dispatcher.PushFrame(frame);
}

public object ExitFrames(object f)
{
    ((DispatcherFrame)f).Continue = false;

    return null;
}

private void ButtonClick(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < 500; i++)
    {
        label.Content = i.ToString();
        DoEvents();
    }
}

- , WPF (, Windows Forms) , .

+7

.

- Application.DoEvents, . , , Thread.Sleep, .

private void button1_Click(object sender, RoutedEventArgs e)
{
        int i = 0;

        while (i < 500)
        {
            label1.Content = i.ToString();
            System.Threading.Thread.Sleep(2000);
            Application.DoEvents();
            ++i;
        }
 }

- Control.BeginInvoke label1.Content =..

0

:

private void button1_Click(object sender, RoutedEventArgs e)
{
        int i = 0;

        while (i < 500)
        {
            label1.Content = i.ToString();
            //Update the UI
            Application.DoEvents();
        //  System.Threading.Thread.Sleep(2000);
            ++i;
        }
 }

. . backgroundworker .

0

" , . . ." - .

, , for , Dispatcher.BeginInvoke.

0

,

Label.Update();
-1

All Articles