System.Net.Sockets.Socket.DisconnectAsync C# (CSharp) Method

DisconnectAsync() public method

public DisconnectAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
        public bool DisconnectAsync(SocketAsyncEventArgs e)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
            bool retval;

            // Throw if socket disposed
            if (CleanedUp)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            // Prepare for the native call.
            e.StartOperationCommon(this);
            e.StartOperationDisconnect();

            SocketError socketError = SocketError.Success;
            try
            {
                socketError = e.DoOperationDisconnect(this, _handle);
            }
            catch
            {
                // clear in-use on event arg object 
                e.Complete();
                throw;
            }

            // Handle completion when completion port is not posted.
            if (socketError != SocketError.Success && socketError != SocketError.IOPending)
            {
                e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None);
                retval = false;
            }
            else
            {
                retval = true;
            }

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
            return retval;
        }

Usage Example

        public static int DestorySocket(Socket socket)
        {
            int r = -1;
            try
            {
                //if (_socket.Connected)
                //{
                //    _socket.Disconnect(false);

                //}
                if (socket != null)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.DisconnectAsync(null);
                    
                    socket.Close();
                    socket.Dispose();
                    socket = null;
                }
                r = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                r = -1;
            }
            return r;
        }