Reputation: 150
After fetching data from the database, I serialize it into XML.
I then write that XML into a Redis caching instance as a string.
I want the endpoint to check if data exists in the cache and based on the result either return the data from the cache, or hit the DB, cache the data and then return that.
My code works just fine when executed synchronously:
Working Synchronous Code
[HttpGet]
public IHttpActionResult Test(int userId)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var data = Cache.StringGet("Cart:" + userId);
if (string.IsNullOrEmpty(data))
{
// Grab data from DB and format as XML
Cache.StringSet("Cart:" + userId, data, TimeSpan.FromHours(2));
}
response.Content = new StringContent(data);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
return new ResponseMessageResult(response);
}
Where everything goes bananas is when trying to make it Asynchronous.
Broken Async Code ( I included the smallest amount of code necessary to reproduce the issue )
[HttpGet]
public async Task<HttpResponseMessage> TestAsync(int userId)
{
var data = await Cache.StringGetAsync("Cart:" + userId);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("<test>Test</test>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
return response;
}
Note that in this example above I'm not even accessing the asynchronously loaded data. If I comment out the await line, things start working again. It only fails if a await is in the code.
The problem that occurs is that 50% of the time, requests to the endpoint just ... stall and never finish. Fiddler screenshot attached to highlight the issue.
Finally, if there is a easier way to skip media formatting and content negotiation, i'd be more than happy to change my approach.
I should add that the service that will consume this endpoint only supports XML, and it made no sense to me to deserialize and reserialize on every request.
Upvotes: 0
Views: 322
Reputation: 150
It ended up being Azure Application Insights.
I guess it does not fully support async or has issues with async in combition with manually creating HttpResponseMessages.
Thank you all for the responses.
Upvotes: 1