![](/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.