开发者

Download file with backgroundWorker

开发者 https://www.devze.com 2023-04-02 21:02 出处:网络
i have created the downloader file private void开发者_StackOverflow中文版 btnTestDownload_Click(object sender, EventArgs e)

i have created the downloader file

private void开发者_StackOverflow中文版 btnTestDownload_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
} 

and work! but

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

the backgroundWorker dos not stop!


CancelAsync does not cause the worker to stop. You have to do that manually. Inside the worker method, you have to periodically check it's CancellationPending property to see if it should cancel or not.

So basically the body of the DoWork method should be something like this:

foreach( var something in somethingelse )
{
  if (worker.CancellationPending == true) {
    e.Cancel = true;
    return;
  }
  //do your work here
}

If you inside your worker method just call some other method that itself takes a long time to complete, and you do not have the possibility to periodically check the CancellationPending variable yourself, then it's not easy to stop the worker on command without forcefully destroying the thread.


See MSDN:

When you call CancelAsync, your worker method has an opportunity to stop its execution and exit. The worker code should periodically check the CancellationPending property to see if it has been set to true.


It sounds like you've got completely the wrong idea about the purpose of a background worker. If you want to download a single file asyncronously with the ability to cancel it, all this functionality is built into the WebClient class.

Background worker is for long running tasks which are, on the whole, processor intensive. For example, if the file you were downloading were a large text file and you needed to parse each line of the text file, you could use the background worker for that, e.g.

Downloading a File

    WebClient Client = new WebClient();

    public void TestStart()
    {
        //Handle the event for download complete
        Client.DownloadDataCompleted += Client_DownloadDataCompleted;
        //Start downloading file
        Client.DownloadDataAsync(new Uri("http://mywebsite.co.uk/myfile.txt"));
    }

    void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        //Remove handler as no longer needed
        Client.DownloadDataCompleted -= Client_DownloadDataCompleted;
        //Get the data of the file
        byte[] Data = e.Result;
    }
    public void TestCancel()
    {
        Client.CancelAsync();
        Client.DownloadDataCompleted -= Client_DownloadDataCompleted;
    }

Processing a File

    BackgroundWorker worker = new BackgroundWorker() { WorkerSupportsCancellation = true };

    //Take a stream reader (representation of a text file) and process it asyncronously
    public void ProcessFile(StreamReader Reader)
    {
        worker.DoWork += worker_DoWork;
        worker.RunWorkerAsync(Reader);
    }
    public void CancelProcessFile()
    {
        worker.CancelAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Get the reader passed as an argument
        StreamReader Reader = e.Argument as StreamReader;
        if (Reader != null)
        {
            //while not at the end of the file and cancellation not pending
            while (Reader.Peek() != -1 && !((BackgroundWorker)sender).CancellationPending)
            {
                //Read the next line
                var Line = Reader.ReadLine();
                //TODO: Process Line
            }
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消