Repository navigation
Description
Apple platform
macOS & iOS
Framework version
net10.0-*
Affected platform version
.NET SDK: 10.0.301
Description
NSUrlSessionHandler appears to convert caller-requested cancellation during response stream reads into a direct TimeoutException.
In the attached repro, HttpClient.Timeout is set to 5 minutes, so the request itself is not timing out. The only timeout-like event is a caller-owned CancellationTokenSource that cancels after 250 ms and is passed to Stream.ReadAsync.
Expected behavior:
- Caller cancellation should surface as
OperationCanceledException/TaskCanceledException. TimeoutExceptionshould be reserved for an actual request timeout, such asHttpClient.Timeoutor a handler-owned timeout.
Actual behavior:
NSUrlSessionHandlerthrowsSystem.TimeoutException.- The inner exception is
System.Threading.Tasks.TaskCanceledException.
For comparison, the same repro using SocketsHttpHandler surfaces TaskCanceledException, which is the behavior I would expect for caller cancellation.
This seems related to the behavior in `NSUrlSessionDataTaskStream.ReadAsync:
macios/src/Foundation/NSUrlSessionHandler.cs
Lines 1493 to 1499 in 4c9e983
| try { | |
| await Task.Delay (50, cancellationToken).ConfigureAwait (false); | |
| } catch (TaskCanceledException ex) { | |
| // add a nicer exception for the user to catch, add the cancelation exception | |
| // to have a decent stack | |
| throw new TimeoutException ("The request timed out.", ex); | |
| } |
Possibly related issue: #20474
Steps to Reproduce
Please see the attached NSUrlSessionTimeoutRepro.zip project.
The repro starts a loopback HTTP server. The server sends response headers and one body byte, then stalls before sending the declared second byte. The client then calls Stream.ReadAsync(buffer, cancellationToken) with a caller-created token that cancels after 250 ms.
The output is displayed in a native text view in the app window.
Run on macOS:
dotnet run -f net10.0-macosRun on iOS simulator:
dotnet run -f net10.0-ios -r iossimulator-arm64Observed output
NSUrlSessionHandler: first read returned 1 byte(s): A
NSUrlSessionHandler: second read threw System.TimeoutException
NSUrlSessionHandler: message: The request timed out.
NSUrlSessionHandler: inner: System.Threading.Tasks.TaskCanceledException: A task was canceled.
SocketsHttpHandler: first read returned 1 byte(s): A
SocketsHttpHandler: second read threw System.Threading.Tasks.TaskCanceledException
SocketsHttpHandler: message: The operation was canceled.
Did you find any workaround?
In app code, I currently need to treat TimeoutException as a possible network/cancellation failure when using NSUrlSessionHandler.
That is not ideal because it makes caller cancellation indistinguishable from a real timeout.
Activity
rolfbjarne commentedon Jun 16, 2026
Thanks for the report! I'll have a look.
[NSUrlSessionHandler] Surface cancelled requests with a better exceptβ¦