Home » Microsoft » 70-487 v.2 » What should you do?
You deploy a RESTful ASP.NET Web API to manage order processing.
You are developing an Azure App Services Web App to consume the API and allow customers to order products. You use the HttpClient object to process order entries. The API throws SocketException errors when the Web App experiences a high volume of concurrent users.
You need to resolve the errors.
What should you do?
A. Implement a Using statement block when declaring the HttpClient object.
B. Increase the value of the Timeout property when declaring the HttpClient object.
C. Use the static modifier to declare the HttpClient object.
D. Create a new HttpClient instance for each API request and use asynchronous method calls.
Correct Answer: C
Explanation/Reference:
If the class that wraps the external resource is shareable and thread-safe, create a shared singleton instance or a pool of reusable instances of the class.
The following example uses a static HttpClient instance, thus sharing the connection across all requests. public class SingleHttpClientInstanceController : ApiController
{ private static readonly HttpClient httpClient; static SingleHttpClientInstanceController()
{
httpClient = new HttpClient();
}
// This method uses the shared instance of HttpClient for every call to GetProductAsync. public async Task<Product> GetProductAsync(string id)
{ var hostName = HttpContext.Current.Request.Url.Host; var result = await httpClient.GetStringAsync(string.Format("http://{0}:8080/api/…", hostName)); return new Product { Name = result };
}
}
References: https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/