Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading