简体   繁体   English

C#WebClient使用Async并返回数据

[英]C# WebClient Using Async and returning the data

Alright, I have ran into a problem when using DownloadDataAsync and having it return the bytes to me. 好吧,我在使用DownloadDataAsync并将字节返回给我时遇到了问题。 This is the code I am using: 这是我正在使用的代码:

    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;
        }
    }

The error I get is "Cannot implicitly convert type 'void' to 'byte[]'" 我得到的错误是“无法将类型'void'隐式转换为'byte []'”

Is there anyway I can make this possible and give me the bytes after it is done downloading? 无论如何,我可以使这成为可能,并在完成下载后给我字节数? It works fine when removing "bytes =". 删除“bytes =”时它工作正常。

Since the DownloadDataAsync method is asynchronous, it doesn't return an immediate result. 由于DownloadDataAsync方法是异步的,因此不会立即返回结果。 You need to handle the DownloadDataCompleted event : 您需要处理DownloadDataCompleted事件:

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
...


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

client.DownloadDataAsync doesn't have a return value. client.DownloadDataAsync没有返回值。 I think you want to get the downloaded data right? 我想你想获得下载的数据吗? you can get it in the finish event. 你可以在完成比赛中得到它。 DownloadProgressChangedEventArgs e , using e.Data or e.Result . DownloadProgressChangedEventArgs e ,使用e.Datae.Result Sorry I forgot the exact property. 对不起,我忘了确切的财产。

DownloadDataAsync returns void so you can't assign it to byte array. DownloadDataAsync返回void,因此您无法将其分配给字节数组。 To access the downloaded bytes you need to subscribe to DownloadDataCompleted event. 要访问下载的字节,您需要订阅DownloadDataCompleted事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM