在HttpWebRequest.BeginGetResponse上设置超时

时间:2012-08-21 06:47:27

标签: c# .net

我有一个类库,我正在移植到Windows 8商店类库。 其中一种方法使用现在不支持的同步HttpWebRequest。 我需要保持方法同步,因为Async工作已经在应用程序而不是库中完成,并且更改它将需要花费很多精力。 我已经使用IAsyncresult将其更改为同步任务,但我不确定如何使用此代码设置请求超时。有人可以帮忙吗? 任何人都可以看到我可能遇到的任何其他问题吗?

//Create Web Request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
IAsyncResult asyncResult = request.BeginGetResponse(null, null);

if (asyncResult.AsyncWaitHandle.WaitOne(5 * 1000))
{
    //Get Response
    using (HttpWebResponse response = request.EndGetResponse(asyncResult) as HttpWebResponse)
    {
        if (request.HaveResponse && response != null)
        {
            using (Stream reader = response.GetResponseStream())
            {
                result = XDocument.Load(reader);
            }
        }
    }
}
else
{
    request.Abort();
}

更新:我已经为请求添加了一个等待句柄,如果超时,我将中止httpwebrequest。这会处理由HttpWebRequest启动的任何线程吗?

1 个答案:

答案 0 :(得分:1)

怎么样:

if(false == request.GetResponseAsync().Wait(DateTime.Now.AddMinutes(2.0)))
{
    Trace.WriteLine("timeout");
    return;
}
//...

现在请记住,这只是等待异步操作的超时。要专门处理响应/请求流操作的超时,请参阅HttpWebRequest.Timeout

您不必将async / await*Async方法一起使用。他们只返回您可以使用的Task<T>对象并使用WaitContinueWith等方法......比处理Begin / {{1更容易(APM模式)......

FWIW End模式称为任务异步模式(TAP)。它现在似乎是推荐的模式,取代了异步编程模型(APM,*Async / Begin)和基于事件的异步模式( EPM,EndCompleted等......)。