0

I'm checking a URL and start a new task to prevent UI freezing.

Like this:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "HEAD"; var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse,null); 

The point is.. I'm implemented a max time (for example 10 seconds). If the app reach 10 seconds without response, the task must be aborted.

4
  • Hint: Start a new thread so that UI do not hang. Then kill thread based on your condition. Commented Jan 17, 2015 at 2:24
  • Check out the proposed solution here Commented Jan 17, 2015 at 2:29
  • Possible solution stackoverflow.com/questions/24980427/… Commented Jan 17, 2015 at 2:32
  • What is the purpose of this code? what are you trying to do? Commented Jan 17, 2015 at 7:08

1 Answer 1

1

HttpWebRequest does not allow you to easily apply a timeout to asynchronous requests.

I recommend you use the more modern HttpClient:

using (var client = new HttpClient()) { client.Timeout = TimeSpan.FromSeconds(10); var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)); } 

If you are stuck in HttpWebRequest land, then you can use a timer that calls Abort (untested):

static async Task<HttpWebResponse> GetResponseWithTimeoutAsync(this HttpWebRequest request, TimeSpan timeout) { // Start request and timeout var delayTask = Task.Delay(timeout); var requestTask = Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null); var completedTask = await Task.WhenAny(delayTask, requestTask); if (completedTask == delayTask) { request.Abort(); throw new TimeoutException(); } return (HttpWebResponse)(await requestTask); } 
Sign up to request clarification or add additional context in comments.

1 Comment

The second solution returns an error in this line: var requestTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null); The call is ambiguous

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.