Im aware of the dispose pattern and would like to properly dispose my Socket resource. In the documentation they recommend to use SafeHandles, but I'm not sure how exactly this works with System.Net.Socket. I discovered that the Socket class itself includes a SafeSocketHandle, but I have no idea how to use it. Do I need to dispose the handle and the socket or is it sufficient to dispose only the handle? And I assume in the class I'm only using the handle for socket operations, right?
public class MySocket : IDisposable
{
private SafeSocketHandle _handle;
private bool _disposed = false;
public MySocket(AddressFamily addressFamily)
{
Socket s = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
_handle = s.SafeHandle;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_handle.Dispose();
}
_disposed = true;
}
}
And maybe someone is also able to explain why SafeHandles should be used? I mean wouldn't this be sufficient?:
public class MySocket : IDisposable
{
private Socket _socket;
private bool _disposed = false;
public MySocket(AddressFamily addressFamily)
{
_socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_socket.Dispose();
}
_disposed = true;
}
}