I have a console app which calls methods like this:
static void Main(string[] args)
{
Test();
}
static async void Test()
{
await SyncADToDBAsync();
}
static async Task SyncADToDBAsync()
{
using (var client = GetHttpClient())
{
try
{
var action = new { Type = "SyncADToDB",
Domains = new string[] { "my.domain" } };
var response = await client.PostAsJsonAsync(
"api/v1/active-directory/actions", action);
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
var x = 0;
}
}
}
However, the console app exits out when I step into the line of code with client.PostAsJsonAsync()
. How can I structure the code so the console app doesn't exit, so the console app waits for the value returned by the service? It looks like the target Web API controller method isn't getting hit by the test call either although the service method was getting hit earlier when I implemented the call using WebClient
instead of HttpClient
.
[W]hy is my code exiting out before method completion for this scenario?
The code is exiting because although SyncADToDBAsync
is waiting for PostAsJsonAsync
to complete, and Test
is waiting for SyncADToDBAsync
to complete, Main
is not waiting for Test
to complete and is thereby exiting too soon.
How can I structure the code so the console app doesn't exit, so the console app waits for the value returned by the service?
We need to tell Main
to wait for Test
to complete. We also need Test
to return a Task
instead of void
, because we can await a Task
but we cannot await void
.
This is probably close to the structure that you are needing:
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args)
{
// use GetAwaiter().GetResult() to prevent
// the program from exiting until after
// the async task(s) have completed.
Test().GetAwaiter().GetResult();
}
static async Task Test()
{
await SyncADToDBAsync();
}
static async Task SyncADToDBAsync()
{
// for the sake of this example,
// we are using Task.Delay(ms) to
// emulate the non-blocking call to the HttpClient
await Task.Delay(1000);
Console.WriteLine("Do something with the response.");
}
}
Here it is as a Fiddle. And here is a GitHub issue that refers to using GetAwaiter().GetResult()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With