1

So I built a small program to consume a REST api, but it never finishes beacuse no data is received. I'm new to using Async and wait commands, so I have probably gotten it wrong somehow. The threads responsible for retrieving the data just times out after a couple of seconds. The url in itself is valid though and no exception seems to be thrown.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Bot_Application1
{
    [Serializable]
    public class ConsumeFOAAS
    {
        private static HttpClient client = new HttpClient();
        private static String message = "empty";


        public String GetMessage()
        {
            RunAsync().Wait();
            return message;
        }


        static async Task RunAsync()
        {
            client.BaseAddress = new Uri("http://foaas.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));

            try
            {
                message = await GetProductAsync("/because/:Insultinator");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }


        static async Task<String> GetProductAsync(string path)
        {
            Debug.WriteLine("Inside GetProductAsync");
            String product = "empty";
            HttpResponseMessage response = await client.GetAsync(path); //<--This never finishes
            Debug.WriteLine("Response: " + response);
            if (response.IsSuccessStatusCode)
            {
                product = await response.Content.ReadAsStringAsync();
            }
            return product;
        }
    }
}
smulan1
  • 19
  • 1

2 Answers2

0

You shouldn't call .Wait(). The best wait to achieve what you want is :

public async Task<String> GetMessage()
{   
    return await RunAsync();
}

And change the RunAsync function :

static async Task<string> RunAsync() {

 client.BaseAddress = new Uri("http://foaas.com/");
 client.DefaultRequestHeaders.Accept.Clear();
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));

 try {
  return await GetProductAsync("/because/:Insultinator");
 } catch (Exception e) {
  Console.WriteLine(e.Message);
 }

}
Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
-1

Deadlock can be caused by task manager. Try using:

RunAsync().ConfigureAwait(false).Wait();

Explanation: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

astef
  • 8,575
  • 4
  • 56
  • 95