![](/img/trans.png)
[英]Tasks/Thread/Delegate.beginInvoke with Thread.Sleep()
[英]How to Thread.Sleep in BeginInvoke
我尝试使用以下代码将TextBox.Text更新为从1到10,内部为1秒。 我不明白为什么整个UI在文本更新为10之前要睡10秒钟,因为Thread.Sleep(1000)应该属于Dispatcher.BeginInvoke创建的单独的后台线程。
我的代码有什么问题?
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();
您的代码仅创建新线程,以强制调度程序将您的操作同步回UI线程。 我想您添加了Dispatcher.BeginInvoke
由于从另一个线程更改mytxt1.Text
导致的异常。 尝试这个:
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);
}
}
设置文本的操作正在UI上运行,这就是UI冻结的原因。
由于只有创建UI控件实例的线程(也称为UI线程)可以修改UI控件的属性的限制,因此您必须运行在UI线程上设置文本的代码。 这就是您正在做的。
您可以尝试的是让该代码在Threading.Timer中运行。
或者...使用已经拥有的代码,您应该具有类似的内容,并且可能会起作用:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.