异步下载时设置用户状态

时间:2009-08-01 09:34:18

标签: c# webclient

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

}

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分: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:已完成