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

时间:2017-05-30 05:22:41

标签: c# winforms backgroundworker

A类包含两个事件buttonStart_ClickbuttonCancel_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;}
              }  
          }  
     }
 }

1 个答案:

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