12

我正在使用此代码来检索 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完成请求?

4

6 回答 6

26

使用 Dot.Net 4.5:

 public static async void GetDataAsync()
        {           
            DoSomthing(await new WebClient().DownloadStringTaskAsync(MyURI));
        }
于 2012-07-18T06:39:50.510 回答
23

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

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

client.DownloadStringAsync(uri);
于 2011-02-21T20:52:34.493 回答
3

msdn 文档

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

挂钩此事件时,您将收到DownloadStringCompletedEventArgs,其中包含带有结果字符串的string属性。Result

于 2011-02-21T20:50:31.187 回答
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;
}
于 2014-12-31T00:53:17.457 回答
0

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

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

于 2011-02-21T20:52:27.953 回答
0

我对 WP7 有同样的问题我解决了这个方法。等待不工作 wp7 但如果你使用 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));

    }
于 2013-04-10T07:26:04.747 回答