I tried to update a TextBox.Text to display from 1 to 10 with an internal of 1 second with the following code. I do not understand why the entire UI sleeps for 10 second before the text is updated to 10, as I though the Thread.Sleep(1000) should belong to a separate background thread created by Dispatcher.BeginInvoke.
What is wrong with my code?
Thread t1 = new Thread(new ThreadStart(
delegate()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
for (int i = 1; i < 11; i++)
{
mytxt1.Text = "Counter is: " + i.ToString();
Thread.Sleep(1000);
}
}));
}));
t1.Start();
Your code creates new thread only to force dispatcher to synchronize your action back to UI thread. I suppose that you added Dispatcher.BeginInvoke due to exception that changing mytxt1.Text from another thread causes. Try this:
Thread t1 = new Thread(new ThreadStart(
delegate()
{
for (int i = 1; i < 11; i++)
{
var counter = i; //for clouser it is important
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
mytxt1.Text = "Counter is: " + counter.ToString();
}));
Thread.Sleep(1000);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With