本文介绍了C#Web客户端使用异步和返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,我一直在使用DownloadDataAsync并让它字节还给我的时候遇到了一个问题。这是code我使用的:
Alright, I have ran into a problem when using DownloadDataAsync and having it return the bytes to me. 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[]'"
反正我有可以让这一切成为可能,并给我字节它完成下载后?取出时它工作正常字节=
Is there anyway I can make this possible and give me the bytes after it is done downloading? It works fine when removing "bytes =".
推荐答案
由于 DownloadDataAsync
方法是异步的,它不返回一个直接结果。您需要处理 DownloadDataCompleted
事件:
Since the DownloadDataAsync
method is asynchronous, it doesn't return an immediate result. You need to handle the DownloadDataCompleted
event :
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
...
private static void DownloadCompleted(Object sender, DownloadDataCompletedEventArgs e)
{
byte[] bytes = e.Result;
// do something with the bytes
}
这篇关于C#Web客户端使用异步和返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!