【问题标题】:Setting the user state when downloading asynchronously异步下载时设置用户状态
【发布时间】:2009-08-01 09:34:17
【问题描述】:

VS 2008 SP1

我正在使用网络客户端异步下载一些文件。

我有 5 个文件要下载。

但是,我想监控每次下载,想把用户状态设置为文件名,所以在ProgressCompletedEvent中可以查看用户状态,看看哪个文件完成了?

他是我正在尝试做的一个简短的代码 sn-p。

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

}

【问题讨论】:

    标签: c# webclient


    【解决方案1】:

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

    【讨论】:

    • client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCallback);Client.UploadFileAsync(uri, "STOR", sourceFile,fileName);私人无效UploadFileCallback(对象发送者,UploadFileCompletedEventArgs e){MessageBox.Show(e.UserState.ToString()); . . . }
    【解决方案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: 完成

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 2016-09-20
      • 2018-05-05
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多