A类包含两个事件buttonStart_Click
,buttonCancel_Click
。单击“开始”按钮时,单击BackgroundWorker
开始进程。
现在当点击取消按钮时,会弹出一个MessageBox,如果用户点击Yes按钮BackgroundWorker
,则停止处理,如果用户点击No按钮,BackgroundWorker将恢复处理。
现在问题出现在bgw.CancelAsync()
CancellationPending
成为现实之后,我想在用户点击留言框中的“否”后将CancellationPending
设为false。
任何人都可以知道我该怎么做或任何其他解决方案?
public partial class A : Form
{
private BackgroundWorker bgw;
private void buttonCancel_Click(object sender, EventArgs e)
{
// Make cancel request
if (bgw != null)
{
bgw.CancelAsync();
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
B objB=new B();
bgw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
bgw.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
bgw.DoWork += new DoWorkEventHandler(objB.Work);
}
}
class B
{
private bool WantToCancle()
{
DialogResult Result= MessageBox.Show("Are you want to cancel?", "Cancel ?",MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
return Result == DialogResult.Yes ? true : false;
}
public void Work(object sender, DoWorkEventArgs e)
{
While(condition...)
{
......
if(((BackgroundWorker)sender).CancellationPending)
{
if(WantToCancle()){return;}
}
}
}
}
答案 0 :(得分:1)
我需要做的就是调用。
private bool WantToCancle()
{
DialogResult Result = DialogResult.Yes;
Application.OpenForms["form name"].Invoke((Func<DialogResult>)(() =>
Result =MessageBox.Show("Are you want to cancel?", "Cancel ?",MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
return Result == DialogResult.Yes ? true : false;
}