1

Even with C#'s garbage collection, I feel I should release resources when done using them. Is this the proper use of dispose to release my ssh client?

            public void Disconnect()
            {
                string _disconnect = "bye";
                _sendCommand = _disconnect;
                SendToCodec(_sendCommand);
                client.Disconnect();
                client.Dispose();
            }
Norm Schaeffer
  • 411
  • 3
  • 9
  • no. you better use `using` statement instead of calling dispose manually http://stackoverflow.com/questions/75401/uses-of-using-in-c-sharp – M.kazem Akhgary Mar 04 '16 at 18:07
  • 3
    @M.kazemAkhgary: That's only really doable when you only need your object in one method. It doesn't seem like that in this case. – Matti Virkkunen Mar 04 '16 at 18:08
  • 3
    The comment about using a `using` isn't helpful since clearly your `client` variable spans methods. The only suggestion I'd make is put the SendToCodec and Disconnect in a `try` and the `Dispose` in a `finally` to ensure it happens even if an exception is thrown. – dmeglio Mar 04 '16 at 18:08
  • @MattiVirkkunen yes, that's correct, the client is spanning 40-60 methods...probably many more by the time I'm done. Thanks for the try...finally suggestion – Norm Schaeffer Mar 04 '16 at 18:29

2 Answers2

1

The purpose of Dispose and friends is to release unmanaged resources which are usually other things than just memory that may cause problems if they stay around until the garbage collector gets around to collecting the object. If the object behaves correctly the non-memory resources will be reclaimed eventually when the GC destroys the object, but that could be a long time later. As an example, a FileStream that is not properly disposed will leave the file open until it's eventually collected, which may prevent others from accessing the file.

As a rule of thumb, if the object in question has a Dispose method, it's usually a good indication you should call it when you're done with it.

Note that in the case of many object such as built-in file and socket objects, there's also an alternate method called something like Close. There is no need to call both Dispose and Close - in fact one will probably just call the other inside. (Example: TcpClient.Close really just calls Dispose inside)

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
1

You should always call Dispose() or use a using statement which automatically calls Dispose() on an object that implements IDisposable. It never hurts and it's better to be safe than sorry. Not only that, but it makes your intention clear to whoever has to support your code after you.

itsme86
  • 19,266
  • 4
  • 41
  • 57