Re: [問題] 迴圈暫停並更新控制項

作者: testSV (喔喔喔喔喔)   2015-02-01 15:40:49
工作要開在別的Thread裡面
為確保Thread在程式結束後會消失 偷懶的話設IsBackground=true
要不然得另外弄flag來同步 e.g. while(IsRunning){....}
另外要注意一點
如果要存取DependencyObject的成員
必須要在同個Thread內呼叫
否則會出現"呼叫執行緒無法存取此物件,因為此物件屬於另一個執行緒。"的錯誤
所以必須透過Dispatcher.Invoke來存取
下面的例子
就是會開個Thread 每隔一秒鐘後會更改Title
因為偷懶 所以直接用匿名delegate做掉
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(
delegate()
{
Int16 i=0;
//做某些事情
while (i<10)
{
System.Threading.Thread.Sleep(1000);
i++;
//直接存取會出錯
//this.Title = i.ToString();
this.Dispatcher.Invoke(
new Action(
delegate()
{
this.Title = i.ToString();
}
)
);
}
}
);
thread.Start();
}
另外針對你的應用
可以用System.Windows.Threading.DispatcherTimer比較快
System.Windows.Threading.DispatcherTimer timer =
new System.Windows.Threading.DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick +=
delegate(object oo, EventArgs ee)
{
i++;
this.Title = i.ToString();
};
timer.Start();

Links booklink

Contact Us: admin [ a t ] ucptt.com