The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Use HttpClient.Timeout when every request made by one client should share a default deadline. Use a CancellationTokenSource when only one operation needs its own limit. If both are active, the shorter limit ends the request. Microsoft documents a default client timeout of 100,000 milliseconds (100 seconds).
Choose the timeout scope first
There are three different controls developers often call an “HTTP timeout,” but they govern different scopes or phases:
- Overall client policy:
HttpClient.Timeoutapplies to requests sent through oneHttpClientinstance. - One-operation deadline: a
CancellationTokenSourcetoken passed to a request can stop that individual operation. - TCP connection establishment:
SocketsHttpHandler.ConnectTimeoutlimits creation of a new connection; it is not an overall request deadline.
Configure the client timeout before starting requests. The property accepts a positive TimeSpan or Timeout.InfiniteTimeSpan. Zero and other non-positive values are invalid. See the Microsoft Learn HttpClient.Timeout reference for the accepted values and default.
Set one timeout for an HttpClient instance
Basic C# example
using System;
using System.Net.Http;
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(10)
};
using HttpResponseMessage response =
await httpClient.GetAsync("https://example.com");
response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body.Length);
The ten-second value is a policy for this instance, not a setting that changes every HttpClient in the process. Set it during client construction or dependency-injection registration, before the first request. The documented default is 100,000 milliseconds (100 seconds), not a guarantee that DNS, connection setup, server processing and response transfer each receive an independent 100-second allowance.
#1 Best Overall
Disable the client-level limit deliberately
using var httpClient = new HttpClient
{
Timeout = Timeout.InfiniteTimeSpan
};
An infinite client timeout transfers responsibility to request cancellation, an outer application deadline, or another policy. Do this only when those controls are present; otherwise a stalled operation can remain pending indefinitely.
Apply a deadline to one request
A request-specific token is useful when most calls can use the client default but one call needs a shorter or longer limit. The token source owns the timer and should be disposed after the operation.
using System;
using System.Net.Http;
using System.Threading;
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using HttpResponseMessage response =
await httpClient.GetAsync("https://example.com", cts.Token);
response.EnsureSuccessStatusCode();
Here, the request has a ten-second token deadline and a 30-second client deadline. The ten-second limit wins. If the client timeout were five seconds, it would win instead. Microsoft describes this shorter-limit rule in the HttpClient.Timeout documentation.
Combine a caller token with a timeout token
Production code commonly needs both a user or shutdown cancellation token and a time limit. Link them so either event cancels the request.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #2
using System;
using System.Net.Http;
using System.Threading;
static async Task<string> GetWithDeadlineAsync(
HttpClient client,
string url,
CancellationToken callerToken)
{
using var timeoutCts = new CancellationTokenSource(
TimeSpan.FromSeconds(10));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
callerToken, timeoutCts.Token);
using HttpResponseMessage response =
await client.GetAsync(url, linkedCts.Token);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(linkedCts.Token);
}
Check callerToken.IsCancellationRequested when handling an OperationCanceledException so a user-initiated cancellation is not reported as a timeout. If your application has a broader operation deadline, pass that token into this method rather than creating unrelated timers.
Understand timeout exceptions by target framework
Do not write one universal catch filter and assume it identifies every timeout. Microsoft documents different exception shapes for different .NET implementations in the HttpClient.PostAsync documentation:
| Target runtime | Documented timeout surface | Practical handling |
|---|---|---|
| .NET Framework | HttpRequestException |
Catch and classify using the framework’s available request/error details. |
| .NET Core | OperationCanceledException without an inner exception |
Compare cancellation-token ownership; do not assume every cancellation is a timeout. |
| .NET 5 and later | OperationCanceledException with a nested TimeoutException |
Inspect InnerException for TimeoutException, while still checking whether the caller token was canceled. |
A version-aware handling pattern
try
{
using HttpResponseMessage response =
await client.GetAsync(url, cancellationToken);
response.EnsureSuccessStatusCode();
}
catch (OperationCanceledException ex) when
(cancellationToken.IsCancellationRequested)
{
// The caller, shutdown path, or linked caller token requested cancellation.
throw;
}
catch (OperationCanceledException ex) when
(ex.InnerException is TimeoutException)
{
// Documented timeout shape for .NET 5 and later.
// Record a timeout and apply retry policy if appropriate.
}
catch (HttpRequestException ex)
{
// Includes the documented timeout shape on .NET Framework,
// plus other transport failures. Inspect context before labeling it a timeout.
throw;
}
The exact distinction depends on which token you own and which target framework you support. Microsoft’s cancellation example is available in Make HTTP requests with the HttpClient. Preserve the original exception and request context in logs; do not convert every OperationCanceledException into a timeout message.
Connection timeout is a separate phase
HttpClient.Timeout covers the request operation as a whole. To limit only the time spent creating a new TCP connection, configure a SocketsHttpHandler:
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsusing System;
using System.Net.Http;
var handler = new SocketsHttpHandler
{
ConnectTimeout = TimeSpan.FromSeconds(5)
};
using var client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
ConnectTimeout matters when a new connection is required. It does not replace the overall request timeout and does not limit server processing or response-body consumption. Microsoft distinguishes these settings in the HttpClient class documentation.
DNS and short-deadline caveats
A very small timeout is not a promise that an exception will be observed at exactly that wall-clock interval. Microsoft notes that DNS resolution can take 15 seconds or more when name resolution is required. Consequently, a hostname lookup combined with a configured timeout below 15 seconds can take 15 seconds or longer to report failure. This is a documented platform behavior, not evidence that your TimeSpan was ignored.
- Use realistic end-to-end budgets for DNS, connection setup, TLS, server work and body transfer.
- Measure elapsed time around the call and log the target host, timeout policy and cancellation source.
- Use connection pooling and a long-lived client strategy so ordinary calls do not repeatedly pay connection setup costs.
Timeout design patterns
Shared policy with per-call overrides
Register one client with a conservative default, then pass a token for exceptional calls. This keeps ordinary call sites simple while making the exception explicit.
Streaming responses
If you use HttpCompletionOption.ResponseHeadersRead, the initial request can complete when headers arrive while reading the body continues afterward. Pass the same cancellation token to content-reading APIs such as ReadAsStreamAsync or ReadAsStringAsync where supported, and enforce an application-level deadline for the complete operation.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #4
Retries
Retry only failures that are safe to retry and use backoff. A timeout does not prove that the server did not process a non-idempotent request; the response may have been lost after server-side work completed. Use idempotency keys or application-specific safeguards for writes.
Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
ArgumentOutOfRangeException while setting Timeout |
Zero or another non-positive value was supplied. | Use a positive TimeSpan or exactly Timeout.InfiniteTimeSpan. |
| Timeout remains close to 100 seconds | The instance still has its documented default. | Set HttpClient.Timeout during setup, before sending requests. |
| Request stops earlier than expected | A request token and client timeout are both active. | Compare both values; the shorter one wins. |
| All cancellations are logged as timeouts | Caller cancellation was not distinguished. | Check the caller or linked token before classifying the exception. |
| A five-second timeout takes much longer during first access to a host | DNS resolution can take 15 seconds or more. | Use realistic budgets and investigate resolver/network behavior. |
| Connection attempts fail quickly but the total call still runs long | ConnectTimeout covers only new TCP connection establishment. |
Configure both connection and overall request policies as needed. |
| Body reading outlives the apparent request timeout | Headers were received before the body was consumed. | Pass cancellation to content-reading methods and apply a deadline to the full workflow. |
Or skip the browser setup
If your actual goal is obtaining a clean screenshot of a URL rather than implementing browser automation around an HTTP call, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result.
One GET request returns PNG, JPEG, WebP or PDF. The API supports full-page captures with lazy images, CSS-selector element captures, device and viewport settings, dark mode, retina scale, custom CSS and JavaScript, waits, request blocking, headers, cookies, user agents, authorization, geolocation, timezone, transparent backgrounds, resizing, TTL caching, signed links, asynchronous jobs, webhooks, bulk capture and a usage API. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
Use the ScreenshotNeo documentation for parameter details. The same request can be made from common runtimes:
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account.
Best Value
Frequently asked questions
Can I change HttpClient.Timeout after requests have started?
Set it during client setup, before sending requests. Treat the value as part of that instance’s policy rather than mutable per-call state.
Which timeout should I use for a single slow endpoint?
Keep the shared client policy and pass a CancellationTokenSource token for that endpoint. The request token makes the exception visible at the call site and leaves unrelated calls unchanged.
Does a timeout prove the server did no work?
No. The client may stop waiting after the server accepted or processed the request. Design retries according to HTTP method semantics and use idempotency protection for operations that can be repeated.
Frequently Asked Questions
Can I change HttpClient.Timeout after requests have started?
Set it during client setup, before sending requests. Treat the value as part of that instance’s policy rather than mutable per-call state.
Which timeout should I use for a single slow endpoint?
Keep the shared client policy and pass a CancellationTokenSource token for that endpoint. The request token makes the exception visible at the call site and leaves unrelated calls unchanged.
Does a timeout prove the server did no work?
No. The client may stop waiting after the server accepted or processed the request. Design retries according to HTTP method semantics and use idempotency protection for operations that can be repeated.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools

