Skip to content

Latest commit

 

History

History
51 lines (33 loc) · 2.28 KB

File metadata and controls

51 lines (33 loc) · 2.28 KB
title HCR006 — HttpClient.Timeout must be a positive TimeSpan
description Assigning HttpClient.Timeout a zero or negative value throws ArgumentOutOfRangeException in the setter.

HCR006

HttpClient.Timeout must be a positive TimeSpan or Timeout.InfiniteTimeSpan.

Why

The HttpClient.Timeout setter validates its value: anything that is not positive and not Timeout.InfiniteTimeSpan throws ArgumentOutOfRangeException immediately. TimeSpan.Zero, default, new TimeSpan(0), negative literals, and negative TimeSpan.FromX results are all guaranteed crashes at the assignment site.

Bad

var client = new HttpClient { Timeout = TimeSpan.Zero };
client.Timeout = TimeSpan.FromSeconds(-5);
client.Timeout = default;

Better

Use a positive timeout sized for the operation:

client.Timeout = TimeSpan.FromSeconds(30);

To delegate timeouts to a resilience pipeline instead, use the documented infinite value:

client.Timeout = Timeout.InfiniteTimeSpan;

Current Detection

The implementation reports assignments and object-initializer entries that set Timeout on a System.Net.Http.HttpClient receiver when the value is provably non-positive: TimeSpan.Zero, default/default(TimeSpan), new TimeSpan(...) with a non-positive constant first argument, TimeSpan.FromX(...) with a non-positive constant argument, or a negated positive TimeSpan factory result. The receiver is validated with Roslyn type information when available, with a syntactic fallback for unresolved snippets that visibly declare an HttpClient receiver. Timeout.InfiniteTimeSpan, positive values, non-constant values, and custom Timeout lookalikes are skipped.

Suppression

There is no legitimate reason to assign a non-positive timeout — the setter always throws. If the diagnostic fires on a computed value the analyzer misread, suppress with a comment explaining the actual value.

References