.NET线程 - HttpWebRequest BeginGetResponse + AutoResetEvent

时间:2010-10-28 06:57:10

标签: c# multithreading

我想知道两者中哪种方法更好实现? 我需要创建一个范围在200到5秒之间的Web请求。我需要继续执行html响应 - 所以需要阻止主线程。

第一种方法

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();
    }
}

第二种方法

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 个答案:

答案 0 :(得分:2)

为什么不在主线程上执行Web请求?如果你想要阻止主线程,这是迄今为止最简单的方法。