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!