Bhess

Async Methods in ASP.NET 4.5

Discussion created by Bhess Employee on Dec 4, 2013

If you're considering using the C# code sample provided in my blog post for accessing the PI System Web API from within ASP.NET, take a look at this post from ASP.NET developer and guru Scott Hanselman.

 

Basically, calling an async method within Page_Load ends up being problematic, since Page_Load is a lifecycle event.  There are two options to work around this.  The first is to follow the instructions in Scott's post to stuff the async call into a RegisterAsyncTask().  This is probably a preferable approach for long term stability, and making sure that your app is kind to your thread pool.

 

The second is to consider creating a synchronous helper method, like: 

 
internal static dynamic MakeRequestSync(string url)
{
    WebRequest request = WebRequest.Create(url);
    WebResponse response = request.GetResponseAsync().Result;
 
    using (StreamReader sw = new StreamReader(response.GetResponseStream()))
    {
        using (JsonTextReader reader = new JsonTextReader(sw))
        {
            return JObject.ReadFrom(reader);
        }
    }
}

 This is a quick and dirty approach, and will allow you to get past the problem as well.

Outcomes