Skip to content

Commit 1da01e0

Browse files
committed
Reduce allocations when setting KeepAlive.
1 parent b6b5c84 commit 1da01e0

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/MySqlConnector/Utilities/SocketExtensions.cs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,24 +48,27 @@ public static void SetKeepAlive(this Socket socket, uint keepAliveTimeSeconds)
4848
return;
4949

5050
// If keepAliveTimeSeconds > 0, override keepalive options on the socket
51-
const int keepAliveIntervalMillis = 1000;
5251
#if !NETCOREAPP3_0
5352
if (Utility.IsWindows())
5453
{
5554
// http://stackoverflow.com/a/11834055/1419658
5655
// Windows takes time in milliseconds
5756
var keepAliveTimeMillis = keepAliveTimeSeconds > uint.MaxValue / 1000 ? uint.MaxValue : keepAliveTimeSeconds * 1000;
58-
var inOptionValues = new byte[sizeof(uint) * 3];
59-
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
60-
BitConverter.GetBytes(keepAliveTimeMillis).CopyTo(inOptionValues, sizeof(uint));
61-
BitConverter.GetBytes(keepAliveIntervalMillis).CopyTo(inOptionValues, sizeof(uint) * 2);
57+
var inOptionValues = new byte[12];
58+
inOptionValues[0] = 1;
59+
inOptionValues[4] = (byte) (keepAliveTimeMillis & 0xFF);
60+
inOptionValues[5] = (byte) ((keepAliveTimeMillis >> 8) & 0xFF);
61+
inOptionValues[6] = (byte) ((keepAliveTimeMillis >> 16) & 0xFF);
62+
inOptionValues[7] = (byte) ((keepAliveTimeMillis >> 24) & 0xFF);
63+
inOptionValues[8] = 0xE8;
64+
inOptionValues[9] = 0x03;
6265
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
6366
}
6467
// Unix not supported: The appropriate socket options to set Keepalive options are not exposd in .NET
6568
// https://github.com/dotnet/corefx/issues/14237
6669
// Unix will still respect the OS Default Keepalive settings
6770
#else
68-
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, keepAliveIntervalMillis / 1000);
71+
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);
6972
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, (int) keepAliveTimeSeconds);
7073
#endif
7174
}

0 commit comments

Comments
 (0)