Socket.Dispose() Method
()
Remarks
Releases the unmanaged resources used by the Socket and optionally releases the managed resources. This method is called automatically when the Socket object is disposed of.
When you finish using a Socket, you should call the Dispose() method to release the resources that it occupies.
If you do not call Dispose(), the resources might not be freed until garbage collection reclaims the Socket object.
The Dispose() method can be called multiple times.
The primary work of Dispose() is done by the Dispose(true) method.
When Dispose() is called, it calls Dispose(true), which disposes of both managed and unmanaged resources.
Subsequent calls to Dispose() do nothing.
Implements
Examples
C# Example
This example demonstrates how to create a Socket, connect it, send data, and then dispose of it using a using statement.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketDisposeExample
{
public static void Main(string[] args)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 11000;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Use a 'using' statement for automatic disposal
using (Socket clientSocket = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp))
{
try
{
clientSocket.Connect(remoteEP);
Console.WriteLine("Connected to server.");
string message = "Hello, server!";
byte[] msgBytes = Encoding.ASCII.GetBytes(message);
clientSocket.Send(msgBytes);
Console.WriteLine("Sent: {0}", message);
// The 'using' statement will automatically call clientSocket.Dispose()
// when the block is exited.
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}
}
Console.WriteLine("Socket has been disposed.");
}
}
VB.NET Example
This example demonstrates how to create a Socket, connect it, send data, and then dispose of it using a Using block.
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Module SocketDisposeExampleVB
Public Sub Main()
Dim ipAddress As IPAddress = IPAddress.Parse("127.0.0.1")
Dim port As Integer = 11000
Dim remoteEP As New IPEndPoint(ipAddress, port)
' Use a 'Using' block for automatic disposal
Using clientSocket As Socket = New Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp)
Try
clientSocket.Connect(remoteEP)
Console.WriteLine("Connected to server.")
Dim message As String = "Hello, server!"
Dim msgBytes As Byte() = Encoding.ASCII.GetBytes(message)
clientSocket.Send(msgBytes)
Console.WriteLine("Sent: {0}", message)
' The 'Using' block will automatically call clientSocket.Dispose()
' when the block is exited.
Catch ex As Exception
Console.WriteLine("Error: {0}", ex.Message)
End Try
End Using
Console.WriteLine("Socket has been disposed.")
End Sub
End Module