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 am trying to update the content of a Label each time a variable is incremented, but what happens is label1’s Content is changed only once and only after the while loop terminates. I thought that the incrementation of the counter variable was so fast that the UI thread could not catch up with it, so I wanted to make the thread idle for 2 seconds, hoping to see label1 change value 500 times. It did not work either. Why?
As others have said, the problem is that you’re blocking the UI thread.
Rather than use the suggestions with
Application.DoEvents, I would suggest that you use aDispatcherTimerto schedule the update. Sample code:(I’m not sure whether
Application.DoEventseven works in WPF, and it’s generally regarded as bad practice anyway. If it does work, I doubt that it’s guaranteed to work in future versions. Mixing the two UIs in the same application just for the sake of this sounds like a really bad idea to me.)You could use a
Timer(eitherSystem.Threading.TimerorSystem.Timers.Timer) but in both cases you’d then need to marshal back to the dispatcher thread anyway.DispatcherTimermakes this simpler – theTickevent is always fired within theDispatcherthread anyway.EDIT: If you really want an equivalent of
DoEvents, here’s code which I’ve verified does work, and is based on the MSDN docs forDispatcher.PushFrameexplaining how to do the equivalent ofApplication.DoEventsbut from WPF:I still wouldn’t recommend this though – WPF (like Windows Forms) is designed on an event-driven way of working.