Impostazione dello stato utente durante il download in modo asincrono
Domanda
VS 2008 SP1
Sto usando il clic web per scaricare alcuni file in modo asincrono.
Ho 5 file da scaricare.
Tuttavia, voglio monitorare ogni download e voglio impostare lo stato dell'utente come nome del file, quindi in ProgressCompletedEvent posso controllare lo stato dell'utente per vedere quale file è stato completato?
È uno snippet di codice breve di ciò che sto cercando di fare.
// 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());
}
Soluzione
Puoi passare qualsiasi oggetto come terzo argomento alla chiamata DownloadFileAsync () e lo riavrai come userState. Nel tuo caso, potresti semplicemente passare il tuo nome file.
Altri suggerimenti
Che ne dici di qualcosa del genere:
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);
}
Nel tuo codice chiamante, potresti avere un codice come questo:
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);
Se non ti dispiace renderlo troppo riutilizzabile, puoi semplicemente abbandonare tutte le funzioni passate tutte insieme e scrivere le espressioni lambda direttamente nel tuo codice:
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);
}
Chiamato due volte, questo ti darà un output simile a questo
/ path / to / file1: 265/265 byte ricevuti (100%)
/ path / to / file1: completato
/ path / to / file2: 2134/2134 byte ricevuti (100%)
/ percorso / a / file2: completato