Windows: a connection accepted while the listening Socket is disposed is dropped without being closed (peer hangs until GC)
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
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
FinishOperationAcceptfails because the listening socket's
handle is already disposed:DangerousAddRefthrowsObjectDisposedException, mapped toOperationAborted, or the
UpdateAcceptContextsetsockoptfails —
SocketAsyncEventArgs.Windows.cs#L1061-L1104; - on that error the accept socket is dropped without
Dispose:_acceptSocket = null;—
SocketAsyncEventArgs.cs#L934-L939; - the caller gets
OperationAbortedand 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
Actionswindows-latestrunner (.NET 10.0.x fromactions/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
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dotnet/runtime
-
area-CodeGen-coreclr untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
dotnet/runtime#138181 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Collections untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
dotnet/runtime#138090 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Text.Json untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
dotnet/runtime#138089 · 1 comment ·
Maintainers usually reply within 1 day
-
area-Setup untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
dotnet/runtime#137376 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Memory untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
dotnet/runtime#137334 · 4 comments ·
Maintainers usually reply within 1 day
Similar issues
-
Add `net10.0`Open
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
dotnet-outdated/dotnet-outdated#871 ·
Maintainers usually reply within 1 day
-
triage/untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
unoplatform/uno#26676 ·
Maintainers usually reply within 1 day
-
.NET bug
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
jhaizhou-ops/S2Arm#2177 · 3 comments ·
Maintainers usually reply within 1 day