using System.Net.Sockets; using System.Threading; // Create a socket and connect to a server Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect("localhost", 8080); // Call BeginDisconnect method to disconnect the socket asynchronously clientSocket.BeginDisconnect(false, new AsyncCallback(DisconnectCallback), clientSocket); Thread.Sleep(5000); // Wait for 5 seconds to complete the disconnect operation // Disconnect Callback method static void DisconnectCallback(IAsyncResult ar) { Socket clientSocket = (Socket)ar.AsyncState; clientSocket.EndDisconnect(ar); }
using System; using System.Net.Sockets; // Create a socket and connect to a server Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect("localhost", 8080); // Call BeginDisconnect method to disconnect the socket asynchronously clientSocket.BeginDisconnect(null, null); // Wait until the socket is completely disconnected while (clientSocket.Connected) {} // Clean up resources clientSocket.Dispose();This example demonstrates how to use the BeginDisconnect method to disconnect a socket connection asynchronously without specifying a callback method. Here, the clientSocket object is created, connected to a server, and then the BeginDisconnect method is called with null parameters. A while loop is added to wait until the socket is completely disconnected. Finally, the Dispose method is called to clean up resources. The Socket.BeginDisconnect method is a part of the System.Net.Sockets namespace in C#.