How to define a more aggressive timeout for HttpWebRequest?

扶醉桌前 提交于 2019-11-27 22:26:00

Below code either will return a HttpWebResponse or null if timed out.

HttpWebResponse response = await TaskWithTimeout(request.GetResponseAsync(), 100);
if(response != null)
{
  ....
}

Task<HttpWebResponse> TaskWithTimeout(Task<WebResponse> task, int duration)
{
    return Task.Factory.StartNew(() =>
    {
        bool b = task.Wait(duration);
        if (b) return (HttpWebResponse)task.Result;
        return null;
    });
}

--EDIT--

Creating an extension method would be even better

public static class SOExtensions
{
    public static Task<T> WithTimeout<T>(this Task<T> task, int duration)
    {
        return Task.Factory.StartNew(() =>
        {
            bool b = task.Wait(duration);
            if (b) return task.Result;
            return default(T);
        });
    }
}

Usage would be:

var response = (HttpWebResponse)await request.GetResponseAsync().WithTimeout(1000);

--EDIT 2--

Another way of doing it

public async static Task<T> WithTimeout<T>(this Task<T> task, int duration)
{
    var retTask = await Task.WhenAny(task, Task.Delay(duration))
                            .ConfigureAwait(false);

    if (retTask is Task<T>) return task.Result;
    return default(T);
}
// Abort the request if the timer fires. 
private static void TimeoutCallback(object state, bool timedOut) { 
    if (timedOut) {
        HttpWebRequest request = state as HttpWebRequest;
            if (request != null) {
              request.Abort();
        }
    }
}

Yes it is the responsibility of the client application to implement its own time-out mechanism. You can do this from the code above which sets the timeout and uses the ThreadPool.RegisterWaitForSingleObject method. See http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort.aspx for the full details. Essentially it does an abort from GetResponse, BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!