.NET Threading - HttpWebRequest BeginGetResponse + AutoResetEvent

I would like to know which of these two approaches is better? I need to create a web request that can range from 200 ms to 5 seconds. I need an html response to continue - so I need to block 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();
            }
        }
+3
source share
1 answer

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

+2
source

Source: https://habr.com/ru/post/1771875/


All Articles