C# WebClient接收的字节数超过TotalByTestOreReceive
我正在远程文件列表上运行任务。C# WebClient接收的字节数超过TotalByTestOreReceive,c#,.net,download,webclient,C#,.net,Download,Webclient,我正在远程文件列表上运行任务。 在每个文件上,我使用aWebClient并执行WebClient.DownloadFileTaskAsync(…) 在WebClient的DownloadProgressChanged处理程序中,我注意到直到任务完成之前,对e.BytesReceived进行求和得到的结果要比通过e.TotalByTestOreReceive得到的大小高得多 有时接收到的字节总数正好是文件大小的两倍,有时则要高得多 我通过e.totalByTestorReceive获得的大小是正确
在每个文件上,我使用
aWebClient
并执行WebClient.DownloadFileTaskAsync(…)
在WebClient
的DownloadProgressChanged处理程序中,我注意到直到任务完成之前,对e.BytesReceived
进行求和得到的结果要比通过e.TotalByTestOreReceive
得到的大小高得多
有时接收到的字节总数正好是文件大小的两倍,有时则要高得多
我通过e.totalByTestorReceive获得的大小是正确的,与我通过ResponseHeaders[“Content Length”]
获得的大小相同,检查真实文件时,我确信大小是正确的
为什么我会得到这些值?为了获得正确的下载进度,是否需要删除标题或其他内容
下载文件的方法有
private async Task DownloadFiles(List<FileDetails> files)
{
await Task.WhenAll(files.Select(p => DownloadFileAsync(p)));
}
以及处理进度的代码:
void MyHandler(object sender, DownloadProgressChangedEventArgs e)
{
//GlobalProgress and GlobalPercentage are global variables
//initialized at zero before the download task starts.
GlobalProgress += e.BytesReceived;
//UpdateDownloadTotal is the sum of the sizes of the
//files I have to download
GlobalPercentage = GlobalProgress * 100 / UpdateDownloadTotal;
}
如果您检查所给示例中的:
请注意,它只是将值报告为“传输进度”。我同意这里的文档可能更全面,因为它有点模棱两可,但对我来说(BytesReceived
显然是“自从我们开始下载以来收到了多少字节”,而不是“自从上次引发此事件以来收到了多少字节”
因此,您不需要累积计数-累积的计数是已经给您的。这就是为什么你会得到过多的计数-如果它下载100k引发事件两次,一次在50k,一次在100k,例如,你的GlobalProgress
将是150k
同意其他意见,但只需使用ProgressPercentage
即可获得百分比
1因为如果y
是预期的总数,而x
只是自上次显示消息以来的增量,则说明y字节下载x
的消息实际上是无用的。是否有标题或其他内容,我必须删除以获得正确的下载进度?-建议“使用ProgressPercentage属性确定已发生的传输百分比。”ProgressPercentage属性为我提供每个处理程序调用的进度百分比。把我收到的百分比加起来,我总共得到了130%÷170%…哦,对了,这并不理想。你能显示报告下载进度的代码吗?@stuartd edited问题是,我有多个异步任务同时运行,但我只想显示总体进度。不管怎样,多亏了你的建议,我理解了这个问题并解开了谜团:现在我自己计算增量,以获得总体进度百分比。
void MyHandler(object sender, DownloadProgressChangedEventArgs e)
{
//GlobalProgress and GlobalPercentage are global variables
//initialized at zero before the download task starts.
GlobalProgress += e.BytesReceived;
//UpdateDownloadTotal is the sum of the sizes of the
//files I have to download
GlobalPercentage = GlobalProgress * 100 / UpdateDownloadTotal;
}
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}