2

I have the following code. The async call never returns anything. Even for google.com.

try
            {
                using (
                    var client = new HttpClient()) { 
                var response = client.GetAsync("http://www.google.com");
                Debug.WriteLine("Coming here1"+response.Result.IsSuccessStatusCode);
                if (response.Result.IsSuccessStatusCode)
                {
                    // by calling .Result you are performing a synchronous call
                    Debug.WriteLine("Coming here1");
                    var responseContent = response.Result.Content;

                    // by calling .Result you are synchronously reading the result
                    string responseString = responseContent.ReadAsStringAsync().Result;

                    //Console.WriteLine(responseString);
                }
                else { Debug.WriteLine("else"); }
            }
            }
            catch(Exception e)
            {
               Debug.WriteLine(e.ToString());
            }
        }
DotNetRussell
  • 9,716
  • 10
  • 56
  • 111
user88975
  • 610
  • 1
  • 9
  • 18
  • Is there a specific reason you're not using WebClient? – DotNetRussell Feb 26 '14 at 17:12
  • NO specfic reason. I heard httpclient is the new one with improvements...I read this http://stackoverflow.com/questions/14435520/why-use-httpclient-for-synchronous-connection and followed – user88975 Feb 26 '14 at 17:14

2 Answers2

0

Try This

try{
     WebClient wc = new WebClient();
     wc.DownloadStringCompleted+= (sender,args) => {
        Debug.WriteLine(args.results);
     };
     wc.DownloadStringAsync(new Uri(@"http://www.Google.com",UriKind.RelativeOrAbsolute));

}
catch(Exception e){ Debug.WriteLine(e.Message); }
DotNetRussell
  • 9,716
  • 10
  • 56
  • 111
  • Sure. Please let me know if you come across any how to use tutorials for Httpclient on phone – user88975 Feb 26 '14 at 17:21
  • But I figured the HttpClient option..here is the working code `code`String strResult = await signUpReq.GetStringAsync(finalUri);`code` – user88975 Feb 26 '14 at 18:39
0

You don't appear to be awaiting your Async call.

Try changing var response = client.GetAsync("http://www.google.com"); to var response = await client.GetAsync("http://www.google.com");

Remember to mark your method as async.

you're also blocking on your async call ReadAsStringAsync().Result. As with client.GetAsync, make sure to await the call instead of blocking with Result. This blog post speaks a bit on the topic.

Read up a bit on async/await. You'll love it once you get the hang of it.

earthling
  • 5,084
  • 9
  • 46
  • 90