Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpClient to post information without waiting for response

I am using HttpClient class in my asp.net web api 2 application to post some information to a endpoint. I just want to post the information without waiting for a response. Is this the right syntax

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    // HTTP POST
    var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
    var response = await client.PostAsJsonAsync("api/products", gizmo);
}
like image 597
SharpCoder Avatar asked Mar 23 '16 22:03

SharpCoder


1 Answers

I just want to post the information without waiting for a response

Not awaiting an async method in WebAPI will result in a runtime exception, as the AspNetSynchronizationContext is aware of any triggered asynchronous operations. If it notices a controller action completes before the async operation has, it will trigger the said exception. More on that in ASP.NET Controller: An asynchronous module or handler completed while an asynchronous operation was still pending

If you want to use a fire and forget semantics, you need to queue the delegate via HostingEnvironment.QueueBackgroundWorkItem if you're using .NET 4.5.2 and above. If not, you can defer to using BackgroundTaskManager

Keep in mind this kind of design isn't really suitable for WebAPI. It doesn't scale if you're triggering this action call frequently. If this style happens often, consider using something more suitable such as a message broker.

like image 173
Yuval Itzchakov Avatar answered Sep 28 '22 16:09

Yuval Itzchakov