DownloadStringAsync等待请求完成

我使用此代码来检索url内容:

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完成请求?

为什么要等待…这将像以前一样阻止GUI!

 var client = new WebClient(); client.DownloadStringCompleted += (sender, e) => { doSomeThing(e.Result); }; client.DownloadStringAsync(uri); 

使用Dot.Net 4.5:

  public static async void GetDataAsync() { DoSomthing(await new WebClient().DownloadStringTaskAsync(MyURI)); } 

从msdn文档 :

下载完成后,将引发DownloadStringCompleted事件。

挂钩此事件时,您将收到DownloadStringCompletedEventArgs ,它包含带有Result string属性Result

这将保持你的gui响应,并更容易理解IMO:

 public static async Task 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; } 

你真的想在同一个线程中等待一个异步方法在你启动之后完成吗? 那么为什么不使用同步版本。

您应该挂接DownloadStringCompleted事件并在那里捕获结果。 然后,您可以将其用作真正的异步方法。

我遇到了与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 callback, string url) { WebClient client = new WebClient(); client.DownloadStringCompleted += (p, q) => { if (q.Error == null) { callback(q.Result); } }; client.DownloadStringAsync(new Uri(url)); }