DownloadStringAsync wait for request completion

Meredith picture Meredith · Feb 21, 2011 · Viewed 26.9k times · Source

I am using this code to retrieve an url content:

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
    }

I want to use DownloadStringAsync because DownloadString hangs the app GUI, but I want to be able to return the result on request. How can I wait until DownloadStringAsync finish the request?

Answer

Guyver picture Guyver · Jul 18, 2012

With Dot.Net 4.5:

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