Skip to content

Use async/await pattern for remote resource requests #55

@jt000

Description

@jt000

In an ASP.NET application there are a limited number of request threads available. When request threads are all used up, then any future requests will be denied (i.e. a DOS attack). A way to mitigate this is to release a thread while I/O operations are occurring allowing re-use of the thread & push an operation back onto the thread pool when the I/O operation completes.

For example, instead of...

        static string GetGoogleHomepage()
        {
            var request = (HttpWebRequest) WebRequest.Create("http://www.google.com");

            var response = request.GetResponse();

            var s = new StringWriter();
            var buffer = new byte[1024];
            using (var stream = response.GetResponseStream())
            {
                int length;
                while ((length = stream.Read(buffer, 0, 1024)) != 0)
                {
                    s.Write(Encoding.UTF8.GetString(buffer, 0, length));
                }
            }

            s.Flush();
            return s.ToString();
        }

... use the async await pattern to allow other requests to re-use the threads while awaiting IO requests...

        static async Task<string> GetGoogleHomepageAsync()
        {
            var request = (HttpWebRequest)WebRequest.Create("http://www.google.com");

            var response = await request.GetResponseAsync();

            var s = new StringWriter();
            var buffer = new byte[1024];
            using (var stream = response.GetResponseStream())
            {
                int length;
                while ((length = await stream.ReadAsync(buffer, 0, 1024)) != 0)
                {
                    await s.WriteAsync(Encoding.UTF8.GetString(buffer, 0, length));
                }
            }

            await s.FlushAsync();
            return s.ToString();
        }

This can be re-used in the synchronous calls to prevent repetitious code and to prevent build breaks by using the Result property (though, don't use this in the async methods since it blocks a thread).

        static string GetGoogleHomepage()
        {
            return GetGoogleHomepageAsync().Result;
        }

For more information on async\await, see http://msdn.microsoft.com/en-us/library/hh191443.aspx

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions