Skip to content

HttpClient Response Stream hangs and doesn't respect timeout (only HttpCompletionOption.ResponseHeadersRead) #36822

@prcdpr

Description

@prcdpr

Description

This is a bug that caused me to waste many hours debugging and is very hard to reproduce.

There are requirements for this bug to happen:

  • Send GET request via HTTPS to download a file from network (Content-Length is up to 4 MB, not larger)
  • Set flag HttpCompletionOption.ResponseHeadersRead
  • Set request cancelation token to 1 minute
  • Have poor internet connection
  • Copy response stream via CopyToAsync to MemoryStream

Sometimes, usually on poor internet connection it happens that Response stream is never closed even though cancelation token is set.

Therefore it causes CopyToAsync to hang forever.

I have found workaround in this article: https://www.danielcrabtree.com/blog/33/gotchas-with-httpclients-cancelpendingrequests-and-timeout-in-net

Workaround is pretty simple, you need to create another cancelation token and close response stream forcibly after timeout.

var cts = new CancellationTokenSource(60000)
cts.Token.Register(() => responseStream.Close());

Configuration

  • .NET Core 3.1
  • Windows 10 Pro x64

Regression?

Don't know.

Other information

In my company I had at least dozen user reports usually from remote workers with poor internet connection that the company's downloader app freezes and stops downloading.

Myself I have never experienced it which is probably because I have fast fiber internet at home.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions