当前位置: 动力学知识库 > 问答 > 编程问答 >

asynchronous - 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. 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 =".

网友答案:

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
}
网友答案:

client.DownloadDataAsync doesn't have a return value. 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. Sorry I forgot the exact property.

网友答案:

DownloadDataAsync returns void so you can't assign it to byte array. To access the downloaded bytes you need to subscribe to DownloadDataCompleted event.

分享给朋友:
您可能感兴趣的文章:
随机阅读: