取消按钮上的BackgroundWorker,然后单击另一个表单 [英] Cancel BackgroundWorker on button click on another Form
问题描述
你好,
在我的mainForm中,我有一个BackgroundWorker.启动bgworker的任务时,我调用WaitDialog,完成时将其关闭.我希望在WaitDialog中有一个取消"按钮,单击该按钮时,通知bgworker任务取消该任务.这就是我在mainForm中调用并显示我的waitDlg的方式:
Hello,
In my mainForm I have a BackgroundWorker. I call a WaitDialog when the task for bgworker is started and close it when completed. I want to have a Cancel button in WaitDialog and when clicked, notify the bgworker task to cancel the task. This is how I call and show my waitDlg in mainForm :
currentState = this.CONNECTING;
backgroundWorker1.RunWorkerAsync();
msg = "Connecting...";
waitDlg.set(msg, "");
if (!waitDlg.IsAccessible)
waitDlg.ShowDialog();
在我的waitDlg中,当用户单击取消"按钮时,目前我设置了一个标志Cancel = true.
我尝试使用EventHadler n cancelbutton并在mainForm中进行处理,但从未调用mainForm的方法.
如何实现这个目标?我花了很多时间在此上,但找不到解决方案.谁能帮我这个.我现在很着急-因为花了很多时间来解决这个问题.
非常感谢您的帮助.
感谢
In my waitDlg, when the user clicks Cancel button, at present I jsut set a flag Cancel = true.
I tried using EventHadler n cancelbutton and that handles in mainForm, but the mainForm''s method is never called.
How to achieve this goal ? I have spent lots of time on this but couldn''t find the solution. Can anyone help me with this. I am kind of in hurry now - as have spend many hrs solving this problem.
Any help is highly appreciated.
Thanks
推荐答案
您应该在返回后台工作程序的主窗体上创建一个公共属性.然后,在进度表中,您应该传递对构造函数中主窗体的引用.在取消按钮事件中,调用bgw的CancelAsync事件,类似这样
You should create a public property on the main form which returns the background worker. Then in your progress form you should pass a reference to the main form in the constructor. In the cancel button event call the bgw''s CancelAsync event, something like this
BackgroundWorker bgw;
public BackgroundWorker formWorker
{
get
{
return bgw;
}
}
public frmParent()
{
InitializeComponent();
bgw = new BackgroundWorker();
bgw.WorkerSupportsCancellation = true;
bgw.DoWork +=new DoWorkEventHandler(backgroundWorker_DoWork);
bgw.RunWorkerAsync();
}
private void bt_add_Click(object sender, EventArgs e)
{
frmProgress progress = new frmProgress(this);
progress.ShowDialog();
}
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker backgroundWorker = sender as BackgroundWorker;
if(backgroundWorker != null)
{
while(!backgroundWorker.CancellationPending)
{
}
if(backgroundWorker.CancellationPending)
{
MessageBox.Show("Cancelled");
e.Cancel = true;
}
}
}
在您的进度表中
In you progress form
frmParent myParent;
public frmProgress(frmParent myParent)
{
InitializeComponent();
this.myParent = myParent;
}
private void button1_Click(object sender, EventArgs e)
{
myParent.formWorker.CancelAsync();
}
希望对您有帮助
Hope this helps
这篇关于取消按钮上的BackgroundWorker,然后单击另一个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!