在 CancelAsync() 请求 backgroundworker 后将 CancellationPending 设置为 false

set CancellationPending to false after CancelAsync() request backgroundworker

Class A 包含两个事件 buttonStart_ClickbuttonCancel_Click。当开始按钮是点击 BackgroundWorker 开始进程。

现在,当单击“取消”按钮时,会弹出一个 MessageBox,如果用户单击“是”按钮,BackgroundWorker 将停止处理,如果用户单击“否”按钮,BackgroundWorker 将继续处理。

现在问题是在 bgw.CancelAsync() CancellationPending 变为 true 之后我想在用户单击消息框中的否后将 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;}
              }  
          }  
     }
 }

我需要做的就是调用。

  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;
   }