Search code examples
c#asynchronousrequesthttprequestdownloadstring

DownloadStringAsync wait for request completion


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?


Solution

  • why would you want to wait... that will block the GUI just as before!

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