views:

46

answers:

1

Hi,

I would like to know which approach among the two is a better implementation ? I need to create a web request which can range between 200ms to 5 seconds. I need the html response to proceed - so need to block on the main thread.

First Approach

string GetResponse()
{

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    IAsyncResult result = request.BeginGetResponse(null, null);    

using (HttpWebResponse httpResponse = (HttpWebResponse)request.EndGetResponse(result))
{
    using (Stream dataStream = httpResponse.GetResponseStream())
    {
        StreamReader reader = new StreamReader(dataStream);
        response = reader.ReadToEnd();
    }
}

Second Approach

string response = string.Empty;
AutoResetEvent waitHandle = null;
void GetResponse(string url)
{
    waitHandle = new AutoResetEvent(false);
    try
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        IAsyncResult asyncResult = request.BeginGetResponse(Callback, request);

        waitHandle.WaitOne();
    }
    catch { }
    finally
    {
        waitHandle.Close();
    }
}

    void Callback(IAsyncResult asyncResult)      
    {           

HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            try
            {
                using (HttpWebResponse httpResponse = (HttpWebResponse)request.EndGetResponse(asyncResult))
                {
                    if (httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        using (Stream dataStream = httpResponse.GetResponseStream())
                        {
                            StreamReader reader = new StreamReader(dataStream);
                            response = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch { }
            finally
            {
                waitHandle.Set();
            }
        }
+1  A: 

Why not execute the web request on the main thread? If you want the main thread to block, this is by far the easiest way to accomplish this.

Pieter
Basically my question should have been is there any advantage in the above approachs in my case ? Would the task be assigned to a IO thread and total execution time reduced ?
No, this will take longer because you have overhead of managing the other thread. Not a lot longer though, but this really is not going to be faster.
Pieter