Why C# fire and forget is not working with http call in an API?

I have two minimal APIs, the receiver one is simple

var app = builder.Build();
app.MapGet("/testing", () =>
{
    Console.WriteLine("Received");
});
app.Run();

The calling API returns 200 but does not make the call:

var app = builder.Build();
app.MapGet("/call", () =>
{
     using var client = new HttpClient();
     client.GetAsync("http://localhost:5215/testing");
});
app.Run();

But this one is returning 200 and after 5 seconds making call, why?

var app = builder.Build();
app.MapGet("/call", () =>
{
    Task.Run(async () =>
    {
        await Task.Delay(5000);
        using var client = new HttpClient();
        await client.GetAsync("http://localhost:5215/testing");
    });
});
app.Run();

>Solution :

Well, your client gets disposed before the request has the chance to go anywhere:

() =>
{
    using var client = new HttpClient();
    client.GetAsync("http://localhost:5215/testing");
}

See that using? When execution leaves the scope, the client gets disposed. This aborts all current requests. If you were awaiting the GetAsync, then the client would only get disposed after the response has been received.

Leave a Reply