0

I have the following. It seems to not be waiting after the request has been sent out in the GetAllProjects. It waits for the response, then doesn't wait for the response content to be read in. NOTE: using nuget package for ReadAsAsync (could have used a json object to deserialize however)

public class Project
{
   public string? Id { get; set; }
   public string? Name { get; set; }
   public string? Url { get; set; }
}

public class Main
{
   public static void Main(string[] args)
   {
      AzureClient ac = new AzureClient();
      var projects = ac.GetAllProjects();
   }
}

public class AzureClient
{
   private readonly HttpClient _client;
   private const string PAT = "myToken";
   private const string API_VERSION = "api-version=5.0";

   public AzureClient()
   {
      _client = new HttpClient()
      {
         BaseAddress = new Uri("some uri"),
         Timeout = TimeSpan.FromSeconds(30)
      };
      // added media type and passed in auth token to _client. client returns 200 on requests
   }   

   public async Task<ICollection<Project>> GetAllProjects()
   {
      var response = await _client.GetAsync("_apis/projects?{API_VERSION }");
      var projects = await response.Content.ReadAsAsync<dynamic>();
      
      return projects.value.ToObject<ICollection<Project>>();
   }
}

1 Answers1

0

You are missing an await here

var projects = await ac.GetAllProjects();

you will also need to make your Main method async

RedJandal
  • 1,203
  • 10
  • 18
  • sorry I had an await initially - thanks for noticing this but this is not the issue –  Apr 20 '21 at 20:18
  • @ktbffhktbffh I have updated my answer as you are calling an async method in your Main method and not awaiting it. – RedJandal Apr 20 '21 at 20:48
  • I see - well the thing is main is not async so how can I have an await in there? is it fine to have main async (I really don't think it would affect anything?) I do believe in C# 7.1 and onwards, they introduced this feature however –  Apr 20 '21 at 20:51
  • @ktbffhktbffh it is fine to have an async as long as you are using C# 7.1 or later. If you need to run an async method inside a sync method have a look at this article https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c – RedJandal Apr 20 '21 at 20:58
  • Fair enough - but why is it I need async anyways? I have two awaits within the method body. I would assume I wouldn't need await in the main method? –  Apr 20 '21 at 21:11