题
VS2008年SP1
我使用网clicent下载了一些文件是异步的。
我有5的文件下载。
然而,我希望监测各个下载,并希望用户设定的国家为名的文件,因此在ProgressCompletedEvent我可以检查户状态,看看哪些文件已经完成?
他是一个短短的码的片段什么我想要做的。
// This function will be called for each file that is going to be downloaded.
// is there a way I can set the user state so I know that the download
// has been completed
// for that file, in the DownloadFileCompleted Event?
private void DownloadSingleFile()
{
if (!wb.IsBusy)
{
// Set user state here
wb.DownloadFileAsync(new Uri(downloadUrl), installationPath);
}
}
void wb_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
Console.WriteLine("File userstate: [ " + e.UserState + " ]");
}
void wb_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("File userstate: [ " + e.UserState + " ]");
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
解决方案
你可以通过任何目的 第三 参数DownloadFileAsync()call,你会把它找回来的userState.在你的情况,你可以简单地通过你的文件。
其他提示
这样的事情怎么样:
private void BeginDownload(
string uriString,
string localFile,
Action<string, DownloadProgressChangedEventArgs> onProgress,
Action<string, AsyncCompletedEventArgs> onComplete)
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged +=
(object sender, DownloadProgressChangedEventArgs e) =>
onProgress(localFile, e);
webClient.DownloadFileCompleted +=
(object sender, AsyncCompletedEventArgs e) =>
onComplete(localFile, e);
webClient.DownloadFileAsync(new Uri(uriString), localFile);
}
在您的调用代码中,您可以使用以下代码:
Action<string, DownloadProgressChangedEventArgs> onProgress =
(string localFile, DownloadProgressChangedEventArgs e) =>
{
Console.WriteLine("{0}: {1}/{2} bytes received ({3}%)",
localFile, e.BytesReceived,
e.TotalBytesToReceive, e.ProgressPercentage);
};
Action<string, AsyncCompletedEventArgs> onComplete =
(string localFile, AsyncCompletedEventArgs e) =>
{
Console.WriteLine("{0}: {1}", localFile,
e.Error != null ? e.Error.Message : "Completed");
};
downloader.BeginDownload(
@"http://url/to/file",
@"/local/path/to/file",
onProgress, onComplete);
如果你不介意让它太可重用,你实际上可以放弃传入的函数,并在代码中直接编写lambda表达式:
private void BeginDownload(string uriString, string localFile)
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged +=
(object sender, DownloadProgressChangedEventArgs e) =>
Console.WriteLine("{0}: {1}/{2} bytes received ({3}%)",
localFile, e.BytesReceived,
e.TotalBytesToReceive, e.ProgressPercentage);
webClient.DownloadFileCompleted +=
(object sender, AsyncCompletedEventArgs e) =>
Console.WriteLine("{0}: {1}", localFile,
e.Error != null ? e.Error.Message : "Completed");
webClient.DownloadFileAsync(new Uri(uriString), localFile);
}
调用两次,这会给你输出像这样的输出
/ path / to / file1:收到265/265字节(100%)
/ path / to / file1:已完成
/ path / to / file2:收到的2134/2134字节(100%)
/ path / to / file2:已完成
不隶属于 StackOverflow