C#BackgroundWorker等到结束

时间:2013-06-21 18:16:42

标签: c# multithreading backgroundworker

我正在从事需要用线程完成的项目。

我有一名后勤工作人员负责这项工作。我想要完成的是当我点击Button3时,我的后台工作人员将重启。我已经尝试等待后台工作者在一段时间内完成Backgroundworker1.IsBusy,但这永远不会结束。当我点击Button3时,我收到错误

  

此BackgroundWorker当前正忙,无法同时运行多个任务

这是我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

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

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

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

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        int x = 0, y = 0, result;

        while (true)
        {
            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                x++;
                y++;
                result = x + y;
                this.label1.Invoke(new MethodInvoker(() => this.label1.Text =     result.ToString()));
            }
        }
    }

}//public partial class Form1 : Form

2 个答案:

答案 0 :(得分:3)

侦听已完成的事件,然后在那里重新启动工作人员 -

private bool restartOnCancel = false;

private void button3_Click_1(object sender, EventArgs e)
{
    restartOnCancel = true;
    backgroundWorker1.CancelAsync();
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if ((e.Cancelled == true) && restartOnCancel)
    {
        restartOnCancel = false;
        backgroundWorker1.RunWorkerAsync();
    }
}

答案 1 :(得分:0)

后台工作程序尚未在RunWorkerAsync调用之前完成。如果按下button3,您可以将方法连接到RunWorkerCompleted事件并在那里调用RunWorkerAsync。