我打算写一个函数DownloadData返回一个字节数组,另一个客户端会调用它来获取字节数组。我的观点是我不希望客户端应用程序正在等待文件下载,所以我需要在异步模式下进行下载。但我很困惑如何做到这一点。
这是我的函数:异步下载文件
public byte[] DownloadData(string serverUrlAddress, string path)
{
if(string.IsNullOrWhiteSpace(serverUrlAddress) || string.IsNullOrWhiteSpace(path))
return null;
// Create a new WebClient instance
WebClient client = new WebClient();
// Concatenate the domain with the Web resource filename.
string url = string.Concat(serverUrlAddress, "/", path);
if (url.StartsWith("http://") == false)
url = "http://" + url;
byte[] data = null;
client.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e)
{
data = e.Result;
};
while (client.IsBusy) { }
return data;
}
提示:'while'循环块.. –
您使用的是什么框架?看起来像你正在等待,直到下载完成,这是异步做这件事的目的 –