【发布时间】:2015-12-16 18:26:02
【问题描述】:
我正在学习任务并行库。我有一些使用 WebClient 类从 Web 下载数据的旧代码。我想将我以前使用Event-based Asynchronous Pattern(EAP) 的代码转换为Task-based Asynchronous Pattern (TAP)
我的旧代码如下:
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();
现在使用任务 API,我有代码:
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?
所以我的问题是:
使用任务方法DownloadDataTaskAsync时,WebClient类是否有内置api可以取消下载并报告下载进度?
【问题讨论】:
标签: c# .net task-parallel-library