如何停止Backgroundworker并关闭表单?

时间:2012-03-29 07:51:35

标签: .net winforms c#-4.0 controls backgroundworker

我希望在运行关闭表单时完全停止BackgroundWorker DoWork()进程。

我已应用以下代码,但在“this.Invoke”中会抛出错误:“在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke。”形式接近。

   private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var dt_Images = db.Rings.Select(I => new { I.PaidRs, I.TypeID, I.RingID, I.CodeNo, Image = Image.FromStream(new MemoryStream(I.Image.ToArray())) }).OrderByDescending(r => r.TypeID);
            foreach (var dr in dt_Images.ThenByDescending(r => r.RingID).ToList())
            {
                BTN = new Button();
                BTN.TextImageRelation = TextImageRelation.TextAboveImage;
                BTN.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
                BTN.AutoSize = true;
                BTN.Name = dr.RingID.ToString();
                BTN.Image = dr.Image;
                BTN.Text = dr.CodeNo.ToString() + "    " + dr.TypeID.ToString();
                this.Invoke(new MethodInvoker(delegate { if (backgroundWorker1 != null) flowLayoutPanel1.Controls.Add(BTN); else return; }));
                BTN.Click += new EventHandler(this.pic_Click);
                this.Invoke(new MethodInvoker(delegate { if (backgroundWorker1 == null) txt_pcs.Text = flowLayoutPanel1.Controls.Count.ToString(); else return;}));
            }
        }

  private void Form_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Escape)
            {
                backgroundWorker1.CancelAsync(); //backgroundworker doesnt stop here
                backgroundWorker1 = null;   //it still invokes the delegate
                this.Dispose();  
            }
        }

如何解决此错误?

请帮帮我。

4 个答案:

答案 0 :(得分:2)

您必须在工作人员中注意取消请求。喜欢

private void DoWork(object sender, DoWorkEventArgs e) 
{ 
 var worker = sender as BackgroundWorker; 

 while (!worker.CancellationPending) 
 { 
   … 
 } 

 if (worker.CancellationPending) 
 { 
  e.Cancel = true; 
 } 
}

答案 1 :(得分:1)

实际问题是在后台线程中调用Invoke之前无法安全地检查表单是否正在关闭。

要解决这个问题,你可以做的是推迟关闭一点,直到后台线程有机会退出主循环。

首先,声明两个标志和一个锁定对象:

private volatile bool _closeRequest = false;
private volatile bool _workerStopped = false;
private readonly object _lock = new object();

然后,当您想要关闭表单时,只需致电Close

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.Escape)
    {
        Close();
    }
}

FormClosing内,检查工作人员是否已停止。此部分必须位于监视器内,以防止在完成后台线程时出现竞争条件(即确保_workerStopped_closeRequest以原子方式更新:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    lock (_lock)
    {
        // if not stopped
        if (!_workerStopped)
        {
            // delay closing
            e.Cancel = true;

            // notify worker
            _closeRequest = true;
        }
    }
    base.OnFormClosing(e);
}

最后,在后台主题中,如果需要,实际关闭表单:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        foreach (var dr in GetImages())
        {
            if (_closeRequest)
                break;

            // ... do stuff
        }
    }
    finally
    {
        lock (_lock)
        {
            // notify we stopped
            _workerStopped = true;

            // if closing was postponed, close now
            if (_closeRequest)
                BeginInvoke(new MethodInvoker(Close));
        }
    }
}

答案 2 :(得分:1)

这是一个简单的程序,我认为,它可以让您了解在BackgroundWorker运行时如何处理表单的关闭:

int i = 0;//This is to show progress.
bool cancel;//This is to notify RunWorkerCompleted to Close() the Form if needed.

public Form1()
{
    InitializeComponent();
    FormClosing += Form1_FormClosing;

    backgroundWorker1.WorkerSupportsCancellation = true;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
    backgroundWorker1.RunWorkerAsync();
}

void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //Since this is executed on the main thread - it is not (as far as I know) going to "race" against the FormClosing.
    if (cancel) Close();
    else Text = "Done";
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (backgroundWorker1.IsBusy)
    {
        cancel = true;
        backgroundWorker1.CancelAsync();
        e.Cancel = true;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.CancelAsync();
}

//This is executed on a separate thread:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    while (!backgroundWorker1.CancellationPending)
    {
        Invoke((Action)(() => Text = (i++).ToString()));
        Thread.Sleep(1000);
    }
    e.Cancel = true;
}

答案 3 :(得分:0)

在DoWork方法中,您必须先检查backgroundWorker1.CancellationPending,然后再开始处理下一张图片。

在允许用户关闭表单之前,您必须等到处理完最后一张图片。

有关如何使用CancellationPendingCancel属性的完整示例,请参阅this MSDN example