C# WebClient 使用异步并返回数据

标签 c# asynchronous download progress-bar

好的,我在使用 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 =”时效果很好。

最佳答案

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

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


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

关于C# WebClient 使用异步并返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3474771/

相关文章:

c# - 如何使用 DDay.iCal 设置时区

javascript - 下载文件保存到磁盘时的浏览器事件

c# - 使用 ServiceStack Rest-API 下载文件

download - 防止直接链接到 .zip 文件

winforms 中的 C# listview 不显示添加的项目

C# 操作 block await 不能按预期工作

c# - TruncateTime(System.Nullable`1[System.DateTime] )' has no supported translation to SQL.'

c# - 异步 : What practices in large classes?

java - ChunkedOutput 一次在浏览器上返回响应

asp.net - New PageAsyncTask 的重载解析失败