Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 310
Meredith Avatar asked Feb 21 '11 20:02

Meredith


4 Answers

With Dot.Net 4.5:

 public static async void GetDataAsync()
        {           
            DoSomthing(await new WebClient().DownloadStringTaskAsync(MyURI));
        }
like image 60
Guyver Avatar answered Nov 06 '22 04:11

Guyver


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);
like image 34
Pauli Østerø Avatar answered Nov 06 '22 05:11

Pauli Østerø


From the msdn documentation:

When the download completes, the DownloadStringCompleted event is raised.

When hooking this event, you will receive DownloadStringCompletedEventArgs, this contains a string property Result with the resulting string.

like image 3
Steven Jeuris Avatar answered Nov 06 '22 05:11

Steven Jeuris


this will keep your gui responsive, and is easier to understand 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;
}
like image 2
user2882366 Avatar answered Nov 06 '22 05:11

user2882366