I'm writing a class library which includes socket operations. I don't want to rely on the consumer to dispose resources after finishing or when an exception is thrown.
Normally I would use the "using" statement, but this doesn't work outside of a local scope. In my case I'm having a class and am using the Socket in many public methods. It is easy to dispose the Socket when the connection ends, but how do I dispose it when exceptions are thrown without the "using" block?
Here is what I came up with: Basically I'm encapsulating every method the user has access to with a try catch block. If an exception happens I dispose the resources before the exception is thrown to the user.
But I'm wondering if there is a better alternative. And if it is bad if I hide this automatic disposing from the library consumer.
public class Foo
{
Socket _socket;
public void method1()
{
try
{
// some work with _socket
}
catch
{
_socket.Dispose();
throw;
}
}
}
You have 2 alternatives:
Either using standard IDisposable
implementation
public class Foo : IDisposable {
Socket _socket;
...
public void method1() {
// working with _socket
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (_socket != null) {
_socket.Dispose();
_socket = null;
}
}
}
public void Dispose() {
Dispose(true);
}
}
Or turning _socket
into local variable:
public void method1() {
using (Socket _socket = new Socket(...)) {
// working with _socket
}
}