Cancel WebClient.DownloadFileAsync operation

What is the best way to cancel a DownloadFileAsync operation?

I have a thread (background worker) that starts the download and manages its other aspects, and I finish when I see that the thread has CancellationPending == true.. After starting the download, the thread will sit and spin until the download is complete or the thread is canceled.

If the stream is canceled, I want to cancel the download. Is there a standard idiom for this? I tried CancelAsync, but I get a WebException (interrupted) from it. I am not sure if this is a clean way to cancel.

Thank.

Edit: first exception and object located in internal thread (call stack):

System.dll! System.Net.Sockets.NetworkStream.EndRead (System.IAsyncResult asyncResult) System.dll! System.Net.PooledStream.EndRead (System.IAsyncResult asyncResult)

+3
source share
1 answer

I'm not sure why you got an exception from calling CancelAsync.

I use WebClient to handle Paralell downloads in our current project, and when CancelAsync is called, the event DownloadFileCompletedis generated by WebClient, where the property Cancelledis true. My event handler looks like this:

private void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        this.CleanUp(); // Method that disposes the client and unhooks events
        return;
    }

    if (e.Error != null) // We have an error! Retry a few times, then abort.
    {
        if (this.retryCount < RetryMaxCount)
        {
            this.retryCount++;
            this.CleanUp();
            this.Start();
        }

        // The re-tries have failed, abort download.
        this.CleanUp();
        this.errorMessage = "Downloading " + this.fileName + " failed.";
        this.RaisePropertyChanged("ErrorMessage");
        return;
     }

     this.message = "Downloading " + this.fileName + " complete!";
     this.RaisePropertyChanged("Message");

     this.progress = 0;

     this.CleanUp();
     this.RaisePropertyChanged("DownloadCompleted");
}

And the cancellation method is simple:

/// <summary>
/// If downloading, cancels a download in progress.
/// </summary>
public virtual void Cancel()
{
    if (this.client != null)
    {
        this.client.CancelAsync();
    }
}
+6
source

All Articles