1

我想用 BackgroundWorker 实现暂停恢复和取消功能。我有一个用户控件,并且所有与后台工作人员相关的代码都写在用户控件中。我只是在流布局控件上添加用户控件,就像用户单击按钮一样多。我无法 使用ManualResetEvent实现暂停和恢复功能,但无论如何我无法做到。所以在这里我粘贴我的用户控件类相关代码和我的表单代码。

public partial class ucBackgroundWorker : UserControl
{
    System.ComponentModel.BackgroundWorker bgWorker = null;
    public event Action<string, EventArgs> Done;
    public event Action<string, EventArgs> Cancel;
    private static bool m_continue = true;
    private ManualResetEvent _resetEvent = new ManualResetEvent(false);
    //Semaphore sWaiter = new Semaphore(0, 1);

    public ucBackgroundWorker()
    {
        InitializeComponent();
        bgWorker = new System.ComponentModel.BackgroundWorker();
        bgWorker.WorkerSupportsCancellation = true;
        bgWorker.WorkerReportsProgress = true;
        bgWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        bgWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    }

    public void Run(int counter)
    {
        if (!bgWorker.IsBusy)
        {
            bgWorker.RunWorkerAsync(counter);
        }
        _resetEvent.Set();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int input = int.Parse(e.Argument.ToString());

        this.BeginInvoke((MethodInvoker)delegate
        {
            lblStatus.Text = "Running";
        });

        for (int i = 1; i <= input; i++)
        {
            _resetEvent.WaitOne();
            Thread.Sleep(500);
            (sender as System.ComponentModel.BackgroundWorker).ReportProgress(i * 10);
            if ((sender as System.ComponentModel.BackgroundWorker).CancellationPending)
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    lblStatus.Text = "Cancel";
                });

                e.Cancel = true;
                return;
            }
        }
        Thread.Sleep(1000);
    }


    // This event handler deals with the results of the 
    // background operation. 
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // First, handle the case where an exception was thrown. 
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message);
        }
        else if (e.Cancelled)
        {
            if (Cancel != null)
                Cancel(this.Name, EventArgs.Empty);
        }
        else
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                lblStatus.Text = "Done";
            });

            if (Done != null)
                Done(this.Name, EventArgs.Empty);
        }
        _resetEvent.Reset();
    }

    // This event handler updates the progress bar. 
    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        pBar.Refresh();
        pBar.Value = e.ProgressPercentage;
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        if (bgWorker.IsBusy)
        {
            bgWorker.CancelAsync();
        }
    }

    private void btnPause_Click(object sender, EventArgs e)
    {
        if (bgWorker.IsBusy)
        {
            if (btnPause.Text.ToUpper() == "PAUSE")
            {
                btnPause.Text = "Resume";
                m_continue = false;
                _resetEvent.Reset();
            }
            else if (btnPause.Text.ToUpper() == "RESUME")
            {

                btnPause.Text = "Pause";
                m_continue = true;
                _resetEvent.Set();

            }
        }
    }
}

    public partial class Form3 : Form
        {
            ucBackgroundWorker ucBgWorker = null;

            public Form3()
            {
                InitializeComponent();
            }

            private void btnStart_Click(object sender, EventArgs e)
            {
                ucBgWorker = new ucBackgroundWorker();
                ucBgWorker.Done += new Action<string, EventArgs>(Worker_Done);
                ucBgWorker.Cancel += new Action<string, EventArgs>(Worker_Cancel);
                flowLayoutPanel1.Controls.Add(ucBgWorker);
                ucBgWorker.Run(10);
            }

            void Worker_Done(string arg, EventArgs evtarg)
            {
                label1.Text =arg + " Done One";
                //System.Threading.Thread.Sleep(1000);
            }

            void Worker_Cancel(string arg, EventArgs evtarg)
            {
                label1.Text = arg + " Cancel Click";
                //System.Threading.Thread.Sleep(1000);
            }

        }

在这里,我附上了 mu UI 的图片。 在此处输入图像描述

4

1 回答 1

2

将属性添加到您的类中,该属性将持有 bool-Sleep 。订阅该更改,如果它是 true,则将 thread.sleep 设置为某个大数字,然后订阅该数字变为 0,如果 bool 仍然为 True,则再次将其设置为大数字。这就是我现在想到的,现在肯定有更好的方法。

于 2013-03-30T19:04:42.630 回答