5

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());

}
4

2 回答 2

11

您可以将任何对象作为第三个参数传递给 DownloadFileAsync() 调用,然后将其作为 userState 取回。在您的情况下,您可以简单地传递您的文件名。

于 2009-08-01T10:31:52.513 回答
2

像这样的东西怎么样:

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:已完成

于 2009-08-01T10:42:00.060 回答