Windows: a connection accepted while the listening Socket is disposed is dropped without being closed (peer hangs until GC)

Open
#138,140 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
22/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
csharp
Domain
networking

Research direction

The leak path is in System.Net.Sockets: SocketAsyncEventArgs.Windows.cs (FinishOperationAccept, around lines 1061-1104) and SocketAsyncEventArgs.cs (around lines 934-939), where the accept socket is set to null on error without being disposed. Start by reading those two spots and confirm the accepted socket is dropped on the OperationAborted path. Done means the accepted socket is closed on that error path, and the repro reports orphans 0 without a GC step.

Written by the indexing model from the issue text.

Description

area-System.Net.Sockets
Description

On Windows, when a listening Socket is disposed while an AcceptAsync is pending, a client whose connect()
completes in that window can get a connection that is never closed: the client sees an established connection with no
data, FIN or RST. It is released only when the GC finalizes the abandoned server-side socket. A client with no timeout
waits until a GC happens to run in the server process; HTTP clients wait out their whole timeout.

We hit it with Kestrel: an HttpClient request to a host that was stopping hung for its full timeout (60 s), 2 times in
1 024 runs (8 test processes at once) of a test that stops and starts a host on the same port under polling. A full GC.Collect() plus
GC.WaitForPendingFinalizers() in the server process released the client within milliseconds.

The path we believe is taken (release/10.0, e35e741; same code on main):

  • AcceptEx completes with a connected accept socket, but FinishOperationAccept fails because the listening socket's
    handle is already disposed: DangerousAddRef throws ObjectDisposedException, mapped to OperationAborted, or the
    UpdateAcceptContext setsockopt fails —
    SocketAsyncEventArgs.Windows.cs#L1061-L1104;
  • on that error the accept socket is dropped without Dispose: _acceptSocket = null; —
    SocketAsyncEventArgs.cs#L934-L939;
  • the caller gets OperationAborted and never sees the socket, so nobody closes the connection until the finalizer runs.
Reproduction Steps

A console app (net10.0), Windows. Each round: a listening socket with one pending AcceptAsync at a time (every
accepted socket is disposed at once), 48 clients connecting around the moment the listener is disposed. A client whose
connect succeeded but whose socket shows neither data nor a close within 2 s is counted as an orphan. Without
--no-gc, a full GC follows, and the orphans that then see a close are counted.

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

var numbers = args.Where(a => !a.StartsWith("--")).ToArray();
var rounds = numbers.Length > 0 ? int.Parse(numbers[0]) : 50;
var clients = numbers.Length > 1 ? int.Parse(numbers[1]) : 48;
var gc = !args.Contains("--no-gc");
int connected = 0, closed = 0, orphans = 0, released = 0;
var sw = Stopwatch.StartNew();
for (var round = 0; round < rounds; round++)
{
    var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
    listener.Listen(512);
    var port = ((IPEndPoint)listener.LocalEndPoint!).Port;
    var loop = Task.Run(async () =>
    {
        while (true)
        {
            Socket s;
            try { s = await listener.AcceptAsync(); }
            catch (Exception e) when (e is SocketException or ObjectDisposedException) { return; }
            s.Dispose();
        }
    });
    using var go = new ManualResetEventSlim();
    var tasks = Enumerable.Range(0, clients).Select(i => Task.Run(async () =>
    {
        go.Wait();
        if (i % 4 != 0) await Task.Delay(i % 3);
        var c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try { await c.ConnectAsync(IPAddress.Loopback, port); }
        catch (SocketException) { c.Dispose(); return (Socket?)null; }
        return c;
    })).ToArray();
    go.Set();
    Thread.Sleep(round % 3);
    listener.Dispose();
    await loop;
    var open = new List<Socket>();
    foreach (var t in tasks)
    {
        if (await t is not { } c) continue;
        connected++;
        // true: data, a close or a reset; false after 2 s: neither
        if (c.Poll(TimeSpan.FromSeconds(2), SelectMode.SelectRead)) { closed++; c.Dispose(); }
        else open.Add(c);
    }
    orphans += open.Count;
    if (open.Count > 0 && gc)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        foreach (var c in open)
            if (c.Poll(TimeSpan.FromSeconds(1), SelectMode.SelectRead)) released++;
    }
    foreach (var c in open) c.Dispose();
}
Console.WriteLine($".NET {Environment.Version}, {Environment.OSVersion}: {rounds} rounds x {clients} clients in {sw.Elapsed.TotalSeconds:0.0} s; " +
                  $"connected {connected}, closed {closed}, orphans (no data, no close in 2 s) {orphans}" +
                  (gc ? $", closed by a full GC {released}" : ", no GC"));
return orphans > 0 ? 1 : 0;

Run: dotnet run -c Release -- 50 48 (with the GC step) and dotnet run -c Release -- 50 48 --no-gc.

Expected behavior

Every client whose connect succeeded sees a close or a reset soon after the listener is disposed: an accepted socket
that cannot be handed to the caller is closed by the runtime (e.g. disposed on the error path), so orphans is 0.

Actual behavior

A few clients per thousand get a connection that is neither served nor closed; all of them are released by a full GC,
which shows the socket was abandoned in managed memory:

.NET 10.0.15, Microsoft Windows NT 10.0.26300.0: 50 rounds x 48 clients in 98.5 s; connected 977, closed 975, orphans (no data, no close in 2 s) 2, closed by a full GC 2
.NET 10.0.15, Microsoft Windows NT 10.0.26300.0: 30 rounds x 48 clients in 61.6 s; connected 574, closed 572, orphans (no data, no close in 2 s) 2, closed by a full GC 2
.NET 10.0.15, Microsoft Windows NT 10.0.26300.0: 50 rounds x 48 clients in 102.5 s; connected 1005, closed 1004, orphans (no data, no close in 2 s) 1, no GC

(The ~2 s per round are likely the clients that connect after the listener is gone: on Windows a connect to a loopback
port with no listener is refused only after about 2 s of retries.)

Regression?

Not known; we have only seen it on .NET 10.

Known Workarounds

A full GC.Collect(); GC.WaitForPendingFinalizers(); after the listener is disposed (in our case, after each stop of
a Kestrel host): the finalizer closes the abandoned socket and the client gets a reset at once.

Configuration
  • .NET 10.0.15, Windows 11 Pro 10.0.26300, x64. The same hang of the Kestrel test was also seen once on the GitHub
    Actions windows-latest runner (.NET 10.0.x from actions/setup-dotnet); the repro itself was run only on the
    first machine.
  • Loopback (127.0.0.1).
Other information

Kestrel's socket transport stops on OperationAborted from AcceptAsync and never sees the socket, so it cannot close
it either. We have not checked Linux or macOS.

Dominant language
C#
Stars
18.5k
Forks
5.8k
Avg merge
2d 18h
Merged PRs (30d)
588

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.