Установка состояния пользователя при асинхронной загрузке
Вопрос
VS 2008 SP1
Я использую веб-клиент для асинхронной загрузки некоторых файлов.
У меня есть 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 (), и вы получите его обратно как 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);
Если вы не возражаете против того, чтобы сделать его многократно используемым, вы можете просто отбросить все переданные функции и записать лямбда-выражения прямо в коде:
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: Завершено
/ путь / к / файлу2: получено 2134/2134 байта (100%)
/ path / to / file2: завершено