This code illustrates the blog article Better timeout handling with HttpClient.
Key features:
- control the timeout per request, rather than globally for all requests
- throw a more sensible exception (
TimeoutException
) when a timeout occurs, instead of the usualOperationCanceledException
Reading the very first part:
This tells me that it's listing suggestions for sharing per-request state with message handlers. A timeout doesn't need to share anything with the actual message handlers in this case. The implementation here is using a
CancellationToken
. Context is key here...A request timeout is not really a request state that needs to be associated with the message handlers. If the class wasn't meant to be inherited from, it wouldn't be designed in such a way that would indicate otherwise (i.e.
protected virtual void Dispose(bool disposing)
). If you're designing for extensibility (which is the end goal here), polluting that Dictionary with timeout information might not be preferred either; and you also have no control over the mutability of the timeout in that Dictionary... Dictionary's areIEnumerable<T>
, which means you'd potentially have to add a special case in your code to ignore the timeout key/value pair if you needed to implement code that enumerates all of the key/value pairs to do certain things with them. With inheritance, you don't have to worry about doing anything differently if you wanted to extend this functionality. If you speculatively use intuition to weigh the benefits and disadvantages here, I would say extensibility via inheritance would make sense. If you feel otherwise, what disadvantages is there?Omissions in the Microsoft documentation don't inherently mean that alternative ways are wrong (even though I think you might've misunderstood the context of the listed suggestions). If you've read enough documentation, you would see that there are even syntax errors on some of those pages. (Not saying the documentation is wrong in this case, but there's plenty of potential for the documentation to miss certain things, in addition to being wrong in other cases.)
In .NET 5.0,
Properties
is marked as Obsolete as well in favor of theOptions
property: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httprequestmessage.properties?view=net-5.0#System_Net_Http_HttpRequestMessage_Properties