0

This is the code of my .NET core 3.1 console application:

using System.Net.Http.Headers; using NumbersConsole.Models; namespace NumbersConsole { class Program { static HttpClient client = new HttpClient(); static void ShowcaseNumber(NumberModel numberModel) { Console.WriteLine("Number: " + numberModel.Number.ToString()); Console.WriteLine("Fact: " + numberModel.Text); Console.ReadLine(); } static async Task<NumberModel> GetNumberModelAsync() { NumberModel number = null; var path = new Uri("http://numbersapi.com/41"); HttpResponseMessage response = await client.GetAsync(path); if (response.IsSuccessStatusCode) { number = await response.Content.ReadAsAsync<NumberModel>(); } return number; } static void Main(string[] args) { RunAsync(); } static async Task RunAsync() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); NumberModel number = new NumberModel(); number = await GetNumberModelAsync(); ShowcaseNumber(numberModel); } } } 

And this is my NumberModel.cs:

namespace NumbersConsole.Models { public class NumberModel { public string Text { get; set; } public int Number { get; set; } } } 

Somehow HttpResponseMessage response = await client.GetAsync(path) does not give a response but instead the program just exits.

I have tried using this answer and this article. I have tried multiple variations of this line of code like HttpResponseMessage response = client.GetAsync(path).Result;

Does someone know what is wrong with my code?

1
  • 6
    You aren't awaiting the async method. So the main method exits. You can change main to have a signature of static async Task Main(string[] args) and await RunAsync(); If you're using C# 7.1 or later. which in .Net Core 3.1 the default is C# 8 Commented Jul 22, 2022 at 16:04

1 Answer 1

3

As stated in my comment, you aren't awaiting the async method, so the calling thread continues execution in main once the await is hit in your RunAsync method, allowing the application to exit without completing.

As of C# 7.1 you can use an async version of the main method, and since you are targeting .Net Core 3.1, the default is C# 8, so the following should be valid:

static async Task Main(string[] args) { await RunAsync(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.