gpt4 book ai didi

c# - 如何取消和进度报告 WebClient.DownloadDataTaskAsync 方法返回的任务?

转载 作者:行者123 更新时间:2023-11-30 14:57:30 24 4
gpt4 key购买 nike

我正在学习任务并行库。我有一些旧代码使用 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,我可以取消下载并报告下载进度?

最佳答案

您可以扩展 WebClient:

public static class WebClientExtensions
{
public static async Task<byte[]> DownloadDataTaskAsync(this WebClient webClient, string address, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

using (cancellationToken.Register(webClient.CancelAsync))
{
return await webClient.DownloadDataTaskAsync(address);
}
}
}

然后调用扩展方法:

var data = await webClient.DownloadDataTaskAsync("http://stackoverflow.com/", cancellationToken);

关于c# - 如何取消和进度报告 WebClient.DownloadDataTaskAsync 方法返回的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com