如何在不阻塞 GUI 的情况下执行后台任务,但将信息传回主线程?
How to perform background task without blocking the GUI but transfer back information to main thread?
我想做以下事情:
- 在 GUI 上有一个按钮和一个 table。
- 当我按下按钮时,任务启动
- 这个任务是一个 while 循环,每次迭代都会给我数据
如何在不阻塞 GUI 的情况下 运行 这个循环并在主 GUI table 中从它的每次迭代中获取数据?这很重要,因为 while 停止条件又是 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
不幸的是这里只做了一次,不是每次迭代。
您走在正确的轨道上。您应该使用后台工作者,但不要等待 RunWorkerCompletedEventHandler,它会在一切都完成时发生。
相反,在循环内定期调用后台工作程序的 ReportProgress 方法。这将触发您可以在 GUI 线程中处理的 ProgressChanged 事件。
尝试设置 BackgroundWorkClass WorkerReportsProgress 属性 并处理 ProgressChanged 事件,如本文所述:
https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx
我想做以下事情:
- 在 GUI 上有一个按钮和一个 table。
- 当我按下按钮时,任务启动
- 这个任务是一个 while 循环,每次迭代都会给我数据
如何在不阻塞 GUI 的情况下 运行 这个循环并在主 GUI table 中从它的每次迭代中获取数据?这很重要,因为 while 停止条件又是 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
不幸的是这里只做了一次,不是每次迭代。
您走在正确的轨道上。您应该使用后台工作者,但不要等待 RunWorkerCompletedEventHandler,它会在一切都完成时发生。
相反,在循环内定期调用后台工作程序的 ReportProgress 方法。这将触发您可以在 GUI 线程中处理的 ProgressChanged 事件。
尝试设置 BackgroundWorkClass WorkerReportsProgress 属性 并处理 ProgressChanged 事件,如本文所述: https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx