1、跨平台兼容
2、避免托管异常降低效率或者炸线程乃至虚拟机
平台兼容:Linux、Windows
函数实现:
#if NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
private static void Shutdown(Socket socket)
{
if (socket == null || socket.SocketType != SocketType.Stream)
{
return;
}
PlatformID platform = Environments.Platform;
if (platform == PlatformID.Win32NT)
{
NativeMethods.win32_shutdown(socket.Handle, SocketShutdown.Send);
}
else if (platform == PlatformID.Unix)
{
NativeMethods.linux_shutdown(socket.Handle, SocketShutdown.Send);
}
else
{
try
{
socket.Shutdown(SocketShutdown.Send);
}
catch (Exception) { }
}
}
P/Invoke 声明:
private static class NativeMethods
{
[Dllimport("ws2_32.dll", SetLastError = false, EntryPoint = "shutdown")]
public static extern SocketError win32_shutdown([In] IntPtr socketHandle, [In] SocketShutdown how);
[Dllimport("libc", SetLastError = false, EntryPoint = "shutdown")]
public static extern SocketError linux_shutdown([In] IntPtr socketHandle, [In] SocketShutdown how);
[Dllimport("libc", SetLastError = false, EntryPoint = "setsockopt")]
public static extern int linux_setsockopt(int socket, int level, int option_name, IntPtr option_value, int option_len);
[Dllimport("ws2_32.dll", SetLastError = false, EntryPoint = "setsockopt")]
public static extern int win32_setsockopt(int s, int level, int option_name, IntPtr optval, int optlen);
}



