C# WebClient使用异步方式返回数据

3

好的,当我使用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 =”,它可以正常工作。
3个回答

8

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为空,该如何处理? - Jake
@Jake,如果请求失败或被取消,则e.Result为null。在尝试获取结果之前,请检查e.Error和e.Cancelled。 - Thomas Levesque

0

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


0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接