I'm not familiar with how exactly async/await work. To try to understand it better, I created a sample code below:
static void Main(string[] args)
{
GetAPI();
Console.WriteLine("Hello");
Console.ReadLine();
}
public static async void GetAPI()
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Get", "application/json");
var response = await client.GetAsync("http://somelinks");
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
Console.ReadLine();
}
}
The GetAPI() method will basically call a an API which return some content in Json format. However, the output that I receive is... surprising, despite the GetAPI() is being called first, "Hello" was being printed first in the Console. When I set the debugger, it seems to me right after it hits the await in the GetAPI(), it will go back to the Main.
How do I print the contents from the API first? In another word, how do I make sure the program finish executing everything in the GetAPI() first?
Additional info:
- I was forced to use
async/awaitbecauseHttpClientonly provides theGetAsyncmethod. - I cannot use
async/awaitinMain. It gives me an error sayingError 1 'ConsumeWebApi.Program.Main(string[])': an entry point cannot be marked with the 'async' modifier
await GetAPI()rather thanGetAPI()? Why isGetAPIasynchronous at all, though? It calls async methods, but why is it async?await GetAPI()becaise it is inMain, you cannot useawaitinMain. Also,HttpClientonly providesGetAsyncmethod.Error 1 'ConsumeWebApi.Program.Main(string[])': an entry point cannot be marked with the 'async' modifierGetApi ().Wait ()in main. It will sync things up I believe.GetApi().Wait()fromMainis all you need to do here. You should not change the internals of theGetApimethod to meet the "special needs" of the console app, and for that reason I'd advise against the accepted answer.