后台工作者表单关闭但未取消异步
我想知道如果我有以下 POC,可能会出现什么问题...
public void DoProcess() // called as Do_Work
{
textUpdater = null;
try
{
SetButtonEnabled(false);
aHandler = new DataHandler();
aHandler.Initialize(_configuration);
aHandler.GetDataFromWebAndSave();
MessageBox.Show("completed");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " \r\n\r\n" + ex.StackTrace);
}
SetButtonEnabled(true);
}
通常,backgroundWorker 进程包含一个循环,可以在其中轻松查看是否调用了 cancel 。就我而言,我无法检查... 假设我关闭 Windows 窗体(包含上面的代码)。一切都会安全结束吗? 如果没有,那我该怎么办? (我想其他方法可能是“使用线程”)。
I want to know what can be problem if i have the following POC...
public void DoProcess() // called as Do_Work
{
textUpdater = null;
try
{
SetButtonEnabled(false);
aHandler = new DataHandler();
aHandler.Initialize(_configuration);
aHandler.GetDataFromWebAndSave();
MessageBox.Show("completed");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " \r\n\r\n" + ex.StackTrace);
}
SetButtonEnabled(true);
}
Usually a backgroundWorker process includes a loop where one can easily see whether cancel is called or not. In my case, i can't check ...
Say I CLOSE the windows form (containing above code). Will everything be terminated safely ??
If not, then how can i do it ?
(i guess other way could be 'use thread').
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
后台工作者的线程过程不必有循环。并且不必取消即可完成。当...进程退出时它就结束了!
当它完成时,
RunWorkerCompleted
将被调用。不过,我在您的调用中发现了一个主要问题:您从后台线程操作 GUI。这是禁忌! GUI 元素的所有操作都必须从创建该元素的线程进行。在您的情况下,使用
ReportProgress()
将状态信息委托给ProgressChanged
处理程序,该处理程序将在前台线程中执行它。此外,正如 Rewinder 所写,您可以从 FormClosing() 中取消工作线程。但是,如果您从不从工作进程中监视
CancellationPending
,那么这是毫无意义的。The thread proc of your backgroundworker doesn't have to have a loop. And it doesn't have to be cancelled to finish. It simply finishes when... the proc exits!
When it finishes,
RunWorkerCompleted
will be called.I see a major problem in your call though: You manipulate your GUI from the background thread. This is a no-no! All manipulations of a GUI element must be made from the thread that created the element. In your case, use
ReportProgress()
to delegate status information to theProgressChanged
handler that will execute it in the foreground thread.In addition, as Rewinder wrote, you can cancel the worker from
FormClosing()
. But if you never monitorCancellationPending
from your worker proc, this is pointless.如果你想确保你的后台工作者被取消,你可以这样做:
If you want to be sure your backgroundworker is cancelled, you can do something like this: