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();
The Action that sets the text is running on the UI thred and that's why the UI is freezing.
Due to the limitation that only the Thread that created the instances of UI controls (a.k.a. the UI thread) can modify properties of UI controls, you have to run the code that sets the text on the UI thread. And that's what you're doing.
What you can try, is to have that code run in a Threading.Timer.
Or...with the code you already have, you should have something like this and it might work:
Thread t1 = new Thread(new ThreadStart(
delegate()
{
for (int i = 1; i < 11; i++)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
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);
}
}
来源:https://stackoverflow.com/questions/13874808/how-to-thread-sleep-in-begininvoke