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

看板C_Sharp (C#)作者 (喔喔喔喔喔)時間10年前 (2015/02/01 15:40), 10年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
工作要開在別的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(); -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.46.79.242 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1422776451.A.210.html ※ 編輯: testSV (114.46.79.242), 02/01/2015 15:48:29
文章代碼(AID): #1KpTY38G (C_Sharp)
文章代碼(AID): #1KpTY38G (C_Sharp)