Is this a proper use of dispose

时间:2016-03-04 18:05:50

标签: c#

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();
            }

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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.