What's the point of Socket.Disconnect(true)?

Viewed 64

MSDN description:

public void Disconnect (bool reuseSocket);

true if this socket can be reused after the current connection is closed; otherwise, false.

Where Socket would be reused? C# developer could reuse it (Connect second time) or winsock (linux sockets) would be reused internally in OS? I thought I could reuse it manually in C# code. For example: I have to handle many remote socket connections to different EP, so I could use ObjectPool<Socket> or smth, take socket from pool, connect it, do stuff, then Disconnect(true) it (if no SocketExceptions) and return it to pool for future reuse.

But I looked into Source code (.NET 5) and discovered the following:

Socket.cs:

public void Disconnect(bool reuseSocket)
        {
            ...

            errorCode = SocketPal.Disconnect(this, _handle, reuseSocket);

            ...
        }

SocketPal.cs:

internal static SocketError Disconnect(Socket socket, SafeSocketHandle handle, bool reuseSocket)
        {
            handle.SetToDisconnected();

            socket.Shutdown(SocketShutdown.Both);
            return reuseSocket ?
                socket.ReplaceHandle() :
                SocketError.Success;
        }

So if reuseSocket == true will be executed socket.ReplaceHandle()

Socket.cs

internal SocketError ReplaceHandle()
        {
            // Copy out values from key options.

... STUFF FOR COPYING SOCKET OPTIONS ...
    
            // Then replace the handle with a new one
            SafeSocketHandle oldHandle = _handle;
            SocketError errorCode = SocketPal.CreateSocket(_addressFamily, _socketType, _protocolType, out _handle);
            oldHandle.TransferTrackedState(_handle);
            oldHandle.Dispose();
            if (errorCode != SocketError.Success)
            {
                return errorCode;
            }

            // And put back the copied settings.  

... STUFF FOR COPYING SOCKET SETTINGS ...

            return SocketError.Success;
        }

So we can see this line SocketError errorCode = SocketPal.CreateSocket(_addressFamily, _socketType, _protocolType, out _handle); Which is just create a new socket. We can find the same line in the Socket.cs ctor()

It turns out that it makes little sense to Socket.Disconnect(true)? And it makes no performance improvements?

0 Answers
Related