1

I have hosted a WebAPI (using latest version) in my VM (has .net framework 4.5.2, Windows Server 2012 R2 with all updates).

WebAPI code returns RSS feed from my Blog (external public URL).

Here is the code for same.

I am using this to Cache WebAPI Output.

[AllowAnonymous]
        [CacheOutput(ServerTimeSpan = 9000, ExcludeQueryStringFromCacheKey = false)]
        [HttpGet]
        public async Task<HttpResponseMessage> GetRecentPost(string type)
        {
            string responseFromServer;
            WebRequest request = null;

            request = WebRequest.Create("My_EXTERNAL_BLOG_URL_HERE");

            using (var response = await request.GetResponseAsync())
            {
                using (var dataStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(dataStream))
                    {
                        responseFromServer = await reader.ReadToEndAsync();
                    }
                }
            }
            return new HttpResponseMessage() { Content = new StringContent(responseFromServer, Encoding.UTF8, ContentType) };
        }

I can see from IIS that few requests stay for very long time.

enter image description here

What can be the reason ? Secondly, I see that the app serves around 300 requests per min. Is it a good practice to have async-await in above code ?

NoobDeveloper
  • 1,877
  • 6
  • 30
  • 55

1 Answers1

0

Your code is correct. Best practices are being used.

There is nothing here that would suggest excessive delays. Apparently, the backend URL responds slowly. You can test this theory by using Fiddler to observe incoming and outgoing HTTP requests. Make sure to configure the Fiddler proxy in the web.config file in case you're using IIS to debug.

You should see that outgoing requests to your blog take a long time.

The IIS window shows that all requests are stuck executing the request handler (which is your code). Apparently, the caching attribute that you applied did not take for some reason. I'm not familiar with that attribute. Isn't there a standard attribute built-in that you can use?

Or, you are simply requesting all different URLs which leads to the cache not coming into play.

The question whether it is a good idea to use await really boils down to a different question: When should we use async IO? I'll summarize my existing detailed response: Use it for operations that take a long time and that are being called frequently. See also this.

This case is a very good use case for async IO. await is the most modern way to implement async IO.

Community
  • 1
  • 1
usr
  • 168,620
  • 35
  • 240
  • 369
  • Use a search engine to find out how to configure Fiddler. It's easy. Search term would be "Fiddler IIS"; I'm not familiar with WebAPI or with CacheCow. Maybe caching works but you are requesting mostly different URLs. – usr Nov 05 '14 at 11:35