Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

c# - Pause/Resume loop in Background worker

I have a loop in Background worker in a Winform Application.

I Just used this Code but it won't resume after the Pause.

In the main Class I use this

System.Threading.ManualResetEvent _busy = new System.Threading.ManualResetEvent(false);

Then in My Start Click I wrote this:

      if (!backgroundWorker1.IsBusy)
            {
                MessageBox.Show("Not Busy"); //Just For Debugg
                _busy.Set();
                Start_Back.Text = "Pause";
                backgroundWorker1.RunWorkerAsync(tempCicle);   
            }
            else
            {
                _busy.Reset();
                Start_Back.Text = "Resume";
            }

            btnStop.Enabled = true;

Then in backgroundworker doWork I wrote this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
     m_addTab addTabsInvoke = addTabUrl2;
      Invoke(addTabsInvoke, "http://www.google.com");
        foreach (something)
                {
                    _busy.WaitOne();

                    if (backgroundWorker1.CancellationPending)
                    {
                        return;
                    }
                    if (tabs.InvokeRequired)
                        {
    ......
    ......

I can't understand why pause works while resume doesn't work. Did I wrong something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My best guess for what you want:

void ResumeWorker() {
     // Start the worker if it isn't running
     if (!backgroundWorker1.IsBusy) backgroundWorker1.RunWorkerAsync(tempCicle);  
     // Unblock the worker 
     _busy.Set();
}

void PauseWorker() {
    // Block the worker
    _busy.Reset();
}

void CancelWorker() {
    if (backgroundWorker1.IsBusy) {
        // Set CancellationPending property to true
        backgroundWorker1.CancelAsync();
        // Unblock worker so it can see that
        _busy.Set();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...