后台工人阶级取消,设置取消挂起标志但不退出
我打电话 obackgroundworker.CancelAsync(); 当前在另一个线程中执行某些工作的后台工作人员,然后使用 while (obackgroundworker.IsBusy == true) 在退出应用程序之前等待它完成(以防用户在线程离开处理时改变主意并且我想干净地关闭)
取消挂起的单位正确设置为 true 但线程不会退出,在工作线程中,我有:
backgroundworker obackgroundworker = (backgroundworker)sender;
if (obackgroundworker.cancellationpending == true)
e.cancel = true;
应该检查取消是否挂起,然后将取消标志设置为 true,我认为这也会导致线程实际终止...?或者当它检测到取消实际上结束时我需要从线程调用一些其他函数吗?
我读过很多使用后台工作人员的示例,与上面完全相同,但没有报告任何问题。
来源:
http://www.albahari.com/threading/part3.aspx http://www.dotneat.net/2009/02/10/BackgroundworkerExample。 ASPX http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx
谢谢
I call
obackgroundworker.CancelAsync();
on a background worker currently doing some work in another thread and then using
while (obackgroundworker.IsBusy == true)
to wait for it to finish before quitting the application (in case the user changes their mind while the thread is away processing and I want to close down cleanly)
The flat for cancellation pending is set to true correctly but the thread doesn't quit, in the worker thread i have:
backgroundworker obackgroundworker = (backgroundworker)sender;
if (obackgroundworker.cancellationpending == true)
e.cancel = true;
which should check to see if a cancellation is pending and then set the cancelled flag to true, and i think that also causes the thread to actually terminate...? or is there some other function I need to call from the thread when it detects a cancellation to actually end?
I've read a lot of examples that use background workers exactly like above and don't report any problems.
Sources:
http://www.albahari.com/threading/part3.aspx
http://www.dotneat.net/2009/02/10/BackgroundworkerExample.aspx
http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
e.Cancel
设置为 true 不会停止BackgroundWorker
的执行,它仅指示操作已取消,以便您可以在RunWorkerCompleted 中检查它事件。您需要通过从
DoWork
事件处理程序返回来停止任务:Setting
e.Cancel
to true doesn't stop the execution of theBackgroundWorker
, it only indicates that the operation was canceled so that you can check it in theRunWorkerCompleted
event. You need to stop the task by returning from theDoWork
event handler :不,仅设置该属性不会导致线程终止。此时您应该从您的方法返回。例如,以下是第一个链接中的代码:
请注意 return 语句,以便该方法完成。
当然,如果您从堆栈深处的某个方法执行此操作,则需要确保调用者也知道终止等 - 但通常对于后台工作线程,它是“顶级”方法无论如何都会检查
CancellationPending
属性,因此通常只需返回就可以了。No, just setting the property won't cause the thread to terminate. You should return from your method at that point. For example, here's code from the first of your links:
Note the return statement, so that the method finishes.
Of course, if you're doing this from some method deep in the stack, you'll need to make sure that the caller knows to terminate as well, etc - but normally for background worker threads, it's the "top level" method that checks the
CancellationPending
property anyway, so usually just returning is fine.