问题
So there are two timeout properties that can be set on HttpClient: HttpClient.TimeOut and WebRequestHandler.ReadWriteTimeout.
The first one is just a timeout for the whole request/response, so if a download/upload takes longer than that, I am out of luck and get cut off in the middle of transfer, no questions asked. This can obviously be overridden by setting the timeout to Infinite, but I am not certain what consequences does that have.
Now the latter (ReadWriteTimeOut) - at least to my understanding - should be propagated all the way down to NetworkStream, where it affects how long a request/response stream can block (be idle) until timeout.
The HttpClient is using asynchronous versions of the HttpWebRequest methods, but as stated here:
In the case of asynchronous requests, it is the responsibility of the client application to implement its own time-out mechanism.
It is not explained at all which time-out mechanism they have in mind (network stream idle timeout? timeout for the whole HTTP GET? etc...), so that makes me greatly confused.
So my question is, how exactly does HttpClient handle network/protocol timeouts? I want to use HttpClient to upload/download potentially large files, so for that I set the HttpClient.TimeOut to infinite. But I am worried that by doing so, the app is at risk of waiting infinitely for some event that the server/network refuses to complete.
回答1:
There are 2 options when you download a file using HttpClient
Use
HttpCompletionOption.ResponseContentRead
on your Get request (that's a default implicit option). ThenHttpClient.Timeout
is effectively applied to the entire download procedure. I suppose that's the case when you thought about Infinite timeoutExplicitly use
HttpCompletionOption.ResponseHeadersRead
on your Get request. ThenHttpClient.Timeout
is applied only to getting Head response without content. After that you could download the content managing timeout at your own, e.g. byresponse.Content.ReadAsStreamAsync()
I suppose the option 2 is what you were seeking of. Just setup a HttpClient.Timeout
to get response from server in reasonable time and then download content
回答2:
Your citation is for HttpWebRequest. However, HttpClient.Timeout (working only in .NET 4.5) is for HttpClient. So, it handles timing out when HttpClient API is used. However, set it to infinite is a bad practice. In that case, internal timeouts are in use which will result in throwing exception after ~10 minutes (if internal timeout values weren't changed in .NET 4.5)
来源:https://stackoverflow.com/questions/29851491/how-exactly-are-timeouts-handled-by-httpclient