【问题标题】:C# WebClient Using Async and returning the dataC# WebClient 使用异步并返回数据
【发布时间】:2010-08-13 07:28:09
【问题描述】:

好的,我在使用 DownloadDataAsync 并将字节返回给我时遇到了问题。这是我正在使用的代码:

    private void button1_Click(object sender, EventArgs e)
    {
        byte[] bytes;
        using (WebClient client = new WebClient())
        {
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
            bytes = client.DownloadDataAsync(new Uri("http://example.net/file.exe"));
        }
    }
    void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100;
        label1.Text = Math.Round(bytesIn / 1000) + " / " + Math.Round(totalBytes / 1000);

        progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
        if (progressBar1.Value == 100)
        {
            MessageBox.Show("Download Completed");
            button2.Enabled = true;
        }
    }

我得到的错误是“无法将类型 'void' 隐式转换为 'byte[]'”

无论如何我可以做到这一点并在下载完成后给我字节吗?删除“bytes =”时效果很好。

【问题讨论】:

    标签: c# asynchronous download progress-bar


    【解决方案1】:

    由于DownloadDataAsync 方法是异步的,它不会立即返回结果。您需要处理DownloadDataCompleted 事件:

    client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
    ...
    
    
    private static void DownloadCompleted(Object sender, DownloadDataCompletedEventArgs e)
    {
        byte[] bytes = e.Result;
        // do something with the bytes
    }
    

    【讨论】:

    • 什么意思不立即返回结果,这样试e.Result为null,怎么处理?
    • @Jake,如果请求失败或被取消,则 e.Result 为 null。在尝试获取结果之前检查 e.Error 和 e.Cancelled。
    【解决方案2】:

    client.DownloadDataAsync 没有返回值。我想你想得到下载的数据吗?您可以在完成事件中获得它。 DownloadProgressChangedEventArgs e,使用e.Datae.Result。抱歉,我忘记了确切的属性。

    【讨论】:

      【解决方案3】:

      DownloadDataAsync 返回 void,因此您不能将其分配给字节数组。要访问下载的字节,您需要订阅DownloadDataCompleted 事件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        • 1970-01-01
        • 2020-12-02
        相关资源
        最近更新 更多