我想做以下事情:如何在不阻塞GUI的情況下執行後臺任務,但將信息傳回主線程?
- 在GUI上有一個按鈕和一個表。
- 當我按下按鈕,任務開始
- 這個任務是一個while循環,讓我在每次迭代
我怎樣才能運行這個循環,並在它的每一次迭代中獲得的數據資料主GUI表,不阻塞GUI?這很重要,因爲while stop條件再次是GUI上的一個按鈕。
我試過使用BackgroundWorker
,但我真的無法弄清楚如何在每次循環迭代時發回數據(???)我可以在最後得到結果,但那不是目標。如果我在一個循環中啓動worker(但在worker中沒有循環),它不起作用。
private void ContinuousCoordinateAquisition(object sender, DoWorkEventArgs e)
{
while (continuousPositionAquisitionFlag == true) // while the monitoring is not stopped, get positions
{
// get xyzwpr world coordinates
robotCoordinatesXYZWPRworld XYZWPRworld = robi.getRobotPosition_xyzwpr_world();
Do something........... retuns values I need in GUI
// sleep for defined time
System.Threading.Thread.Sleep(1000); // wait
}
}
主叫將是
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(ContinuousCoordinateAquisition);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ContinuousCoordinateAquisitionCompleted);
continuousPositionAquisitionFlag
從按鈕(停止鍵)來設置。 ContinuousCoordinateAquisitionCompleted
這裏只做一次不幸的是,不是每一次迭代。
_Reactive Extensions_是你的朋友 – MickyD 2015-04-01 13:28:55
對BGW有ProgressChanged事件,完美將數據提交給主線程。 – 2015-04-01 13:34:51
但是,如果每個循環暫停1000毫秒,您可能更適合使用計時器。 – 2015-04-01 13:35:59