Skip to content

HttpClient/WinHttpHandler can't cancel slow response stream reads #17315

Closed

Description

@davidsh

Was part of #14761 list items

Register callback on cancellation token to cancel WinHTTP operation for WinHttpRequestStream, WinHttpResponseStream

Creating separate issue for this.

Cancelling an http request where the response headers arrive slowly works correctly. However, if the response headers arrive fast but the reads from the response body are slow, then the cancellation doesn't really work and still takes a long time. Both HttpClient.Timeout or cancellation token Cancel() doesn't work correctly against the WinHttpResponseStream.ReadAsync() method.

[Fact]
public async Task GetIncludesReadingResponseBody_CancelUsingTimeout_TaskCanceledInShortTime()
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    using (var client = new HttpClient())
    {
        client.Timeout = new TimeSpan(0, 0, 1);

        Task<HttpResponseMessage> getResponse =
            client.GetAsync(s_fastHeadersSlowBodyServer, HttpCompletionOption.ResponseContentRead);

        try
        {
            await getResponse;
            _output.WriteLine("GetAsync() success");
        }
        catch (TaskCanceledException)
        {
            _output.WriteLine("TaskCanceledException");
        }
        finally
        {
            stopwatch.Stop();
            _output.WriteLine("Time to complete GetAsync(): {0}", stopwatch.Elapsed.ToString());
        }
    }
}

[Fact]
public async Task GetIncludesReadingResponseBody_CancelUsingToken_TaskCanceledInShortTime()
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    var cts = new CancellationTokenSource();
    using (var client = new HttpClient())
    {
        Task<HttpResponseMessage> getResponse =
            client.GetAsync(s_fastHeadersSlowBodyServer, HttpCompletionOption.ResponseContentRead, cts.Token);

        Task ignore = Task.Delay(1000).ContinueWith(_ =>
        {
            _output.WriteLine("Calling cts.Cancel() at: {0}", stopwatch.Elapsed.ToString());
            cts.Cancel();
        });

        try
        {
            await getResponse;
            _output.WriteLine("GetAsync() success");
        }
        catch (TaskCanceledException)
        {
            _output.WriteLine("TaskCanceledException");
        }
        finally
        {
            stopwatch.Stop();
            _output.WriteLine("Time to complete GetAsync(): {0}", stopwatch.Elapsed.ToString());
        }
    }
}

[Fact]
public async Task ResponseStreamRead_CancelUsingToken_TaskCanceledInShortTime()
{
    var stopwatch = new Stopwatch();

    stopwatch.Start();
    using (var client = new HttpClient())
    using (HttpResponseMessage response =
        await client.GetAsync(s_fastHeadersSlowBodyServer, HttpCompletionOption.ResponseHeadersRead))
    {
        stopwatch.Stop();
        _output.WriteLine("Time to get headers: {0}", stopwatch.Elapsed.ToString());
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var cts = new CancellationTokenSource();

        Stream stream = await response.Content.ReadAsStreamAsync();
        byte[] buffer = new byte[ResponseBodyLength];

        Task ignore = Task.Delay(1000).ContinueWith(_ =>
        {
            _output.WriteLine("Calling cts.Cancel() at: {0}", stopwatch.Elapsed.ToString());
            cts.Cancel();
        });

        stopwatch.Restart();
        try
        {
            await stream.ReadAsync(buffer, 0, buffer.Length, cts.Token);
            _output.WriteLine("ReadAsync() success");
        }
        catch (TaskCanceledException)
        {
            _output.WriteLine("TaskCanceledException");
        }
        finally
        {
            stopwatch.Stop();
            _output.WriteLine("Time to complete response stream read: {0}", stopwatch.Elapsed.ToString());
        }
    }
}

Activity

  1. self-assigned this
    on May 17, 2016
  2. davidsh commented on May 18, 2016

    @davidsh
    ContributorAuthor

    Split into separate bugs.

  3. transferred this issue fromdotnet/corefxon Jan 31, 2020
  4. added this to the 1.0.0-rtm milestone on Jan 31, 2020
  5. ghost locked as resolved and limited conversation to collaborators on Dec 31, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions