문제
vs 2008 sp1
Web 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 () 호출에 대한 인수는 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