From 16a69dfa7e03366538f3bcfe72455f4c41f9bca4 Mon Sep 17 00:00:00 2001 From: Laveesh Bansal Date: Fri, 2 Jan 2026 22:12:05 -0800 Subject: [PATCH] Socket.SendFile throws InvalidOperationException when Blocking=false The behavior of SendFile on non-blocking sockets is undefined (Windows blocks anyway, Linux may send partial data), so we now throw InvalidOperationException early. --- .../src/System/Net/Sockets/Socket.cs | 7 +++++++ .../tests/FunctionalTests/SendFile.cs | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index 4f5598eac020d0..3b62533e7a82e6 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -1325,6 +1325,13 @@ public void SendFile(string? fileName, ReadOnlySpan preBuffer, ReadOnlySpa ThrowIfDisposed(); + // SendFile is not supported on non-blocking sockets. + // ValidateBlockingMode() below checks for async mismatch; this checks explicit non-blocking. + if (!Blocking) + { + throw new InvalidOperationException(SR.net_sockets_blocking); + } + if (!IsConnectionOriented || !Connected) { throw new NotSupportedException(SR.net_notconnected); diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendFile.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendFile.cs index f85d68d05c8b13..7788a14530347b 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendFile.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendFile.cs @@ -37,6 +37,18 @@ public async Task NotConnected_ThrowsNotSupportedException() await Assert.ThrowsAsync(() => SendFileAsync(s, null, null, null, TransmitFileOptions.UseDefaultWorkerThread)); } + [Fact] + public void SendFile_NonBlockingSocket_ThrowsInvalidOperationException() + { + (Socket client, Socket server) = SocketTestExtensions.CreateConnectedSocketPair(); + using (client) + using (server) + { + client.Blocking = false; + Assert.Throws(() => client.SendFile(null)); + } + } + [Theory] [InlineData(false)] [InlineData(true)]