3

My ASP.NET MVC project reads from and writes to DB through a Web API. Based on my research I plan to build a static utility class to avoid HttpClient to be frequently instantiated/disposed and sockets running out. In a simplified form:

public static class WebApiCalls
{
    private static HttpClient _client;

    static WebApiCalls()
    {
        //initializing _client

    }

    public static Ticket GetTicket(int ticketId)
    {
        var response = _client.GetAsync("<route to web api GetTicket>/" + ticketId).Result;

        //checking response code...

        return JsonConvert.DeserializeObject<Ticket>(response.Content.ReadAsStringAsync().Result);
    }

    public static string SaveTicket(Ticket ticket)
    {
        var content = new StringContent(JsonConvert.SerializeObject(ticket), Encoding.UTF8, "application/json");

        var response = _client.PostAsync("<route to web api SaveTicket>", content).Result;

        //checking response code...

       return response.Content.ReadAsStringAsync().Result; //ticketId
    }
}

Is this implementation thread safe? Could responses get mixed up when two requests from ASP.NET MVC to GetTicket at the same time? I'm still trying to get a hang of topics about static methods, thread safe and lock, etc.

Thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Q. Young
  • 45
  • 5
  • 1
    It is thread safe. Also, depending on your requirements you might consider using [IHttPClientFactory](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1) – jira May 09 '20 at 18:34
  • [Is HttpClient safe to use concurrently?](https://stackoverflow.com/questions/11178220) – aepot May 09 '20 at 18:34
  • Thanks to all! For now I will move forward with this simple implementation and invest some future time into more advanced techniques. – Q. Young May 09 '20 at 21:12

0 Answers0