How can I cancel and progress report a task that returned by WebClient.DownloadDataTaskAsync method?

Viewed 2056

I'm learning task-parallel-library. I have some old code that use WebClient class to download data from web. I want to convert my previous code that using Event-based Asynchronous Pattern(EAP) to Task-based Asynchronous Pattern (TAP)

My old code were below:

WebClient client1 = new WebClient();
client1.DownloadDataCompleted += (o, e)=>
{
    if (e.Cancelled)
    {
        //code that update UI report download has been canceled.
    }
    else
    {
        byte[] s = e.Result;
        //code that update UI report downloads has been completed.
    }
};

client1.DownloadProgressChanged += ( o,  e) =>
{
    //code that update UI report downloading progress.
    updateProgress(e.ProgressPercentage);
};

//start download asynchronous
client1.DownloadDataAsync(new Uri("http://stackoverflow.com/"));

//code to cancel download.
client1.CancelAsync();

Now using Task API, I had code:

WebClient client2 = new WebClient();
Task<byte[]> task = client2.DownloadDataTaskAsync("http://stackoverflow.com/");

task.ContinueWith((antecedent) =>
{
    byte[] s = antecedent.Result;
    //code that updateUI report download has been completed.
});

//TODO how to code that can cancel the download and report progress?

So My questions are:

When using the task method DownloadDataTaskAsync, does the WebClient class has build-in api that I can cancel the download and report the download progress?

3 Answers
Related