Как насчет этого:
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);
}
При двойном вызове вы получите что-то вроде этого
/ путь / к / файлу1: получено 265/265 байт (100%)
/ путь / к / файлу1: Завершено
/ путь / к / файлу2: получено 2134/2134 байта (100%)
/ путь / к / файлу 2: Завершено