在form1的顶部
Stopwatch sw = new Stopwatch();
然后
private void btnDownload_Click(object sender, EventArgs e)
{
//urll.Add("http://download.thinkbroadband.com/1GB.zip");
label7.Text = "Downloading images";
var v = lines.Where(s => s.Contains("Name")).Select(s => s.Substring(15));
var q = lines.Where(s => s.Contains("Code")).Select(s => s.Substring(15));
var r = q.Where(c => c == "is").Concat(q.Where(c => c != "is"));
var p = v.Where(c => c == "Israel").Concat(v.Where(c => c != "Israel"));
var n = r.Count();
int i = 0;
var results = p.ToList();
downloadFile(ExtractImages.imagesUrls);
}
private Queue<string> _downloadUrls = new Queue<string>();
private async void downloadFile(IEnumerable<string> urls)
{
foreach (var url in urls)
{
_downloadUrls.Enqueue(url);
}
await DownloadFile();
}
private async Task DownloadFile()
{
if (_downloadUrls.Any())
{
WebClient client = new WebClient();
client.DownloadProgressChanged += ProgressChanged;
client.DownloadFileCompleted += Completed;
var url = _downloadUrls.Dequeue();
await client.DownloadFileTaskAsync(new Uri(url), @"C:\Temp\TestingSatelliteImagesDownload\" + count + ".jpg");
return;
}
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// Calculate download speed and output it to labelSpeed.
label3.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
}
已完成的活动
long bytesFromCompletedFiles = 0;
// The event that will trigger when the WebClient is completed
private async void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
}
else
{
ProgressBar1.Value = 100;
count++;
bytesFromCompletedFiles += totalBytes[count -1];
await DownloadFile();
}
}
问题是我从不启动sw(秒表)并且从不在任何地方停止/重置它。 所以在行:
label3.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
我在sw上看到无限的标志
问题是我应该在哪里开始/停止/重置sw?
现在,当我正在运行程序时,我没有在label3上看到任何内容,我猜是因为无限,而且我没有启动sw(秒表)。
答案 0 :(得分:4)
在您开始下载之前启动Stopwatch
是有意义的,因为如果您提前启动它会产生错误的结果
private async Task DownloadFile()
{
if (_downloadUrls.Any())
{
WebClient client = new WebClient();
[...]
sw = Stopwatch.StartNew();
await client.DownloadFileTaskAsync(new Uri(url), @"C:\Temp\TestingSatelliteImagesDownload\" + count + ".jpg");
return;
}
}
在下载取消或完成下载后停止
// The event that will trigger when the WebClient is completed
private async void Completed(object sender, AsyncCompletedEventArgs e)
{
if ([...])
{
[...]
}
else
{
[...]
}
sw.Stop();
}