Skip to content

Instantly share code, notes, and snippets.

@JakeGinnivan
Created November 10, 2012 06:20
Show Gist options
  • Select an option

  • Save JakeGinnivan/4050156 to your computer and use it in GitHub Desktop.

Select an option

Save JakeGinnivan/4050156 to your computer and use it in GitHub Desktop.
//Need http://nuget.org/packages/Microsoft.Bcl.Async
internal static class WebRequestExtensions
{
internal static Task<WebResponse> GetResponseAsync(this WebRequest request, TimeSpan timeout)
{
var asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
var timeoutTask = TaskEx.Delay(timeout);
return TaskEx.WhenAny(asyncTask, timeoutTask)
.ContinueWith<WebResponse>(t=>
{
if (t == timeoutTask)
{
asyncTask.ContinueWith(t1=>Trace.WriteLine(t1.Exception.ToString())); // Observe exception if request fails
throw new TimeoutException();
}
return ((Task<WebResponse>)t).Result;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment