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
I'm sorry, I still don't understand your point on this. If the value of the timeout is not shared with the message handler, then it cannot kill the request once the timeout is reached. This isn't even a difference between the inheritance approach and the property bag approach, if, I assume, you mean the same approach as the user above who first asked about inheritance, that we "check if the HttpRequestMessage is of that derived type and grab the timeout from there". In either case, we need to do what I mean by "share": expose information that belongs to the request to the message handler, so it can act accordingly.
Perhaps you can share some code that clarifies what you're saying about having a request-specific timeout without the handler having access to what that timeout is, because I haven't been able to think of a way to do that that makes sense.
I would think this is a point in favor of the property bag. If I've already subclassed HttpRequestMessage to add some other property, or received an HttpRequestMessage from a third-party library that I can't modify or inherit, then the inheritance approach doesn't allow me to add timeouts to this request. On the other hand, every subclass of HttpRequestMessage has the same property bag, so I can add any number of property-based extensions and support them by composing the HttpClientHandlers that handle them. It's similar to a Python mixin class, and arguably the more extensible option. Problems like having to slightly update the property bag syntax for .NET 5.0 or picking a sufficiently unique string key are trivial to solve in comparison.