Skip to content

NSUrlSessionHandler.Dispose doesn't fully clean up #24376

@dotMorten

Description

@dotMorten

Apple platform

iOS

Framework version

net10.0-*

Affected platform version

.NET 8, 9 and 10

Description

When I try and create a background configuration for my NSUrlSessionHandler, I can't dispose that handler and create a new one later, since all requests will start timing out.

Steps to Reproduce

  1. Run the following code more than once. After the first time, all requests will time out:
NSUrlSessionHandler handler = new NSUrlSessionHandler(NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("id"));
 var client = new HttpClient(handler);
 await client.GetByteArrayAsync("https://microsoft.com"); // Times out after the first run
 client.Dispose();
 handler.Dispose();

Did you find any workaround?

I can workaround it with reflection, which is too risky for deployment, but it does clearly indicate what the fix will be:

var field = typeof(NSUrlSessionHandler).GetField("session", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
NSUrlSession session = (NSUrlSession)field.GetValue(handler)!;
session.InvalidateAndCancel();

Judging from this, we just need to add that InvalidateAndCancel call to the Dispose method. There's also FinishTasksAndInvalidate which would fix the timeout, but when I call Dispose on SocketsHttpHandler, and pending requests are cancelled, so the InvalidateAndCancel seems most appropriate.

Relevant logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions