简体   繁体   中英

How do i cancel a backgroundworker operation and how to pause/continue a backgroundworker?

I have a button that start the backgroundworker:

private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
            button1.Enabled = false;
            button2.Enabled = true;
        }

A button to cancel the backgroundworker:

private void button2_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            button1.Enabled = true;
            button2.Enabled = false;
        }

The backgroundworker dowork.progresschanged.completed events:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgw = (BackgroundWorker)sender;
            if (bgw.CancellationPending == true)
            {
                return;
            }
            else
            {
                Parseanddownloadfiles();
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblStatus.Text = "Downloading Filename: " + e.UserState.ToString();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            stopwatch.Stop();
        }

And last the method Parseanddownloadfiles()

private void Parseanddownloadfiles()
        {
            using (WebClient client = new WebClient())
            {
                client.DownloadFile(mainurl, path_exe + "\\page.html");
            }
            HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc = hw.Load(path_exe + "\\page.html");
            foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
            {
                string hrefValue = link.GetAttributeValue("href", string.Empty);
                if (hrefValue.Contains("US"))
                {
                    string url = "http://www.testing.com" + hrefValue;
                    parsedlinks.Add(url);
                }
            }

            for (int i = 0; i < parsedlinks.Count; i++)
            {
                try
                {
                    using (WebClient client = new WebClient())
                    {
                        string filename = parsedlinks[i].Substring(71);
                        client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
                        backgroundWorker1.ReportProgress(0, filename);
                    }
                }
                catch (Exception err)
                {
                    string error = err.ToString();
                }
            }
        }

The important thing now is to make the cancel to work and then if it's possible to make the pause/continue after it.

Change your method int order to check the condition inside the loops into :

private void Parseanddownloadfiles()
{
    using (WebClient client = new WebClient())
    {
        client.DownloadFile(mainurl, path_exe + "\\page.html");
    }
    HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc = hw.Load(path_exe + "\\page.html");
    foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
    {
        string hrefValue = link.GetAttributeValue("href", string.Empty);
        if (hrefValue.Contains("US"))
        {
            string url = "http://www.testing.com" + hrefValue;
            parsedlinks.Add(url);
        }
        if (bgw.CancellationPending == true)
             return;

    }

    for (int i = 0; i < parsedlinks.Count &&  bgw.CancellationPending == false; i++)
    {
        try
        {
            using (WebClient client = new WebClient())
            {
                string filename = parsedlinks[i].Substring(71);
                client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
                backgroundWorker1.ReportProgress(0, filename);
            }
        }
        catch (Exception err)
        {
            string error = err.ToString();
        }
    }

If you need to cancel the downloads, my favorite solution would be to use some Tasks and a CancellationTokenSource.

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM