How to specify a timeout value in HttpWebRequest.BeginGetResponse without blocking the stream

I am trying to issue web requests asynchronously. I have my code working fine, except for one thing: There seems to be no built-in way to specify a timeout on BeginGetResponse. MSDN example clearly shows a working example, but the disadvantage is that they all end

SomeObject.WaitOne()

Which once again clearly states that it blocks the flow. I will be in a high-load environment and cannot block, but I also need a request timeout if it takes more than 2 seconds. With the exception of creating and managing a separate thread pool, is there anything already in the framework that can help me?

Launch Examples:

I would like the async call to not be BeginGetResponse()called after my timeout parameter has expired, indicating that a timeout has occurred.

Apparently, the obvious parameter is TimeOutnot executed for asynchronous calls. The parameter ReadWriteTimeoutdoes not turn on until the response returns. A generic solution would be preferred.

EDIT:

Here's what I came up with: after the call, BeginGetResponseI create Timerwith my duration and end the "start" phase of processing. Now either the request will be completed and my “final” stage will be called OR the waiting period will expire.

, "" - . "-" - , . , "end" EndGetResponse, . "" , , "-" .

, , -. , . 1-3 , (, , ), , . "" .

?

int completed = 0;

this.Request.BeginGetResponse(GotResponse, this.Request);
this.timer = new Timer(Timedout, this, TimeOutDuration, Timeout.Infinite);

private void Timedout(object state)
{
    if (Interlocked.Increment(ref completed) == 1)
    {
        this.Request.Abort();
    }
    this.timer.Change(Timeout.Infinite, Timeout.Infinite);
    this.timer.Dispose();
}

private void GotRecentSearches(IAsyncResult result)
{
    Interlocked.Increment(ref completed);
}
+3
4

, - , .

0

BackgroundWorker, HttpWebRequest , . , , .

ManualResetEvent.WaitOne(), : HttpWebRequest.BeginGetResponse().

0

? /-/ ?

(, )? , , "N" ( -, ), , ( - ), .

, /.

, "N" , "N" , ( ) .

, , ThreadPool.SetTimerQueueTimer() . .

, .

0
source

If you can use async / wait then

private async Task<WebResponse> getResponseAsync(HttpWebRequest request)
        {
            var responseTask = Task.Factory.FromAsync(request.BeginGetResponse, ar => (HttpWebResponse)request.EndGetResponse(ar), null);
            var winner = await (Task.WhenAny(responseTask, Task.Delay(new TimeSpan(0, 0, 20))));
            if (winner != responseTask)
            {
                throw new TimeoutException();
            }
            return await responseTask;
        }
0
source

Source: https://habr.com/ru/post/1729668/


All Articles