1

可能重复:
如何使用按钮启动和停止连续运行的后台工作程序

我有 2 个按钮,第一个按钮名为“Continuous”.. 第二个按钮“Stop”

我想在按下连续按钮时调用一个方法:

private void continuous_Click(object sender ,EvantArgs e) 

      {   

     // continuous taking pictures ...

      }

我的问题是:如何通过按停止按钮来停止执行?

我已经写了一个拍照的代码,我已经成功拍照了......现在我想让相机连续拍摄......但是如果我按下停止按钮,相机应该停止拍照......

我用过BackGroundWorker,但代码不起作用!!!

这是代码:

private void ContinousSnaps_Click(object sender, EventArgs e)
    {

        Contiguous.DoWork += Contiguous_DoWork;
        Contiguous.RunWorkerCompleted += Contiguous_RunWorkerCompleted;
        Contiguous.RunWorkerAsync();
    }

    private void Contiguous_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; ; i++) TakeSnapShotCommand();
    }

    private void Contiguous_RunWorkerCompleted(object sender,
                                   RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show("complete");
    }

    //------------------------------------------------------------------//

    private void Stop_Click(object sender, EventArgs e)
    {
        Contiguous.CancelAsync();


    }

  //--------------------------------------------------------------------//

我怎样才能达到我想要的结果?!

4

1 回答 1

4

试试看这是否可行:在您的 _DoWork 事件中:

    private void Contiguous_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; ; i++)
        {
            if (Contiguous.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            TakeSnapShotCommand();
        }
    }

并在 Stop_Click 中执行以下操作:

    private void Stop_Click(object sender, EventArgs e)
    {
        if (Contiguous.WorkerSupportsCancellation)
            Contiguous.CancelAsync();
    }

还要确保你允许取消(如果你想在这里接受我的建议 - 在表单加载中移动这些事件注册,所以它们将被执行一次,而不是每次单击按钮时 - 只留下 Continuous.RunWorkerAsync() ):

    // your form load <---
    private void Form1_Load(object sender, EventArgs e)
    {
        Contiguous.DoWork += Contiguous_DoWork;
        Contiguous.RunWorkerCompleted += Contiguous_RunWorkerCompleted;
        Contiguous.WorkerSupportsCancellation = true; // allowing cancellation
    }

    private void ContinousSnaps_Click(object sender, EventArgs e)
    {
        // not a bad idea if you disable the button here at this point
        Contiguous.RunWorkerAsync();
    }
于 2013-01-26T04:05:51.287 回答