我正在使用此代码检索网址内容:
private ArrayList request(string query)
{
ArrayList parsed_output = new ArrayList();
string url = string.Format(
"http://url.com/?query={0}",
Uri.EscapeDataString(query));
Uri uri = new Uri(url);
using (WebClient client = new WebClient())
{
client.DownloadStringAsync(uri);
}
// how to wait for DownloadStringAsync to finish and return ArrayList
}
我想使用DownloadStringAsync
,因为DownloadString
挂起了应用GUI,但我希望能够在request
上返回结果。我怎么能等到DownloadStringAsync
完成请求?
答案 0 :(得分:26)
使用Dot.Net 4.5:
public static async void GetDataAsync()
{
DoSomthing(await new WebClient().DownloadStringTaskAsync(MyURI));
}
答案 1 :(得分:23)
为什么要等待...这将像以前一样阻止GUI!
var client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
doSomeThing(e.Result);
};
client.DownloadStringAsync(uri);
答案 2 :(得分:3)
下载完成后,会引发DownloadStringCompleted事件。
在举办此活动时,您会收到DownloadStringCompletedEventArgs,其中包含string
属性Result
,其中包含结果字符串。
答案 3 :(得分:2)
这将使你的gui保持敏感,并且更容易理解IMO:
public static async Task<string> DownloadStringAsync(Uri uri, int timeOut = 60000)
{
string output = null;
bool cancelledOrError = false;
using (var client = new WebClient())
{
client.DownloadStringCompleted += (sender, e) =>
{
if (e.Error != null || e.Cancelled)
{
cancelledOrError = true;
}
else
{
output = e.Result;
}
};
client.DownloadStringAsync(uri);
var n = DateTime.Now;
while (output == null && !cancelledOrError && DateTime.Now.Subtract(n).TotalMilliseconds < timeOut)
{
await Task.Delay(100); // wait for respsonse
}
}
return output;
}
答案 4 :(得分:0)
你真的想在同一个线程中等待一个异步方法在你启动之后完成吗?那么为什么不直接使用同步版本。
您应该挂接DownloadStringCompleted事件并在那里捕获结果。然后你可以将它用作真正的异步方法。
答案 5 :(得分:0)
我遇到了与WP7相同的问题我解决了这个方法。如果你使用Action,那么你将使用Action回调异步函数
public void Download()
{
DownloadString((result) =>
{
//!!Require to import Newtonsoft.Json.dll for JObject!!
JObject fdata= JObject.Parse(result);
listbox1.Items.Add(fdata["name"].ToString());
}, "http://graph.facebook.com/zuck");
}
public void DownloadString(Action<string> callback, string url)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
callback(q.Result);
}
};
client.DownloadStringAsync(new Uri(url));
}