Created
November 10, 2012 06:20
-
-
Save JakeGinnivan/4050156 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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