Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Waiting for a request to finish in C# 4.5

Tags:

c#

I have a http request in my asp.net 4.0 application. I would like for the thread to wait before it continues on.

HttpClient client = new HttpClient();
HttpResponseMessage responseMsg = client.GetAsync(requesturl).Result;

// I would like to wait till complete.

responseMsg.EnsureSuccessStatusCode();
Task<string> responseBody = responseMsg.Content.ReadAsStringAsync();
like image 578
user516883 Avatar asked Jun 11 '12 17:06

user516883


2 Answers

Call .Wait() on the responseBody Task

like image 71
Robert Levy Avatar answered Sep 20 '22 18:09

Robert Levy


In 4.5 (your title says so) you can use async/await

public async void MyMethod()
{
    HttpClient client = new HttpClient();
    HttpResponseMessage responseMsg = await client.GetAsync("http://www.google.com");

    //do your work
}

To download a string you can simply use

public async void Question83()
{
    HttpClient client = new HttpClient();
    var responseStr = await client.GetStringAsync("http://www.google.com");

    MessageBox.Show(responseStr);

}
like image 40
L.B Avatar answered Sep 18 '22 18:09

L.B