Do I have to store a TcpClient even though I only care about its stream?
A new instance of a TcpClient connects to a remote host. Its NetworkStream is retrieved and stored. Do I have to store the TcpClient itself as well to make sure it is not garbage collected?
In case you're going to answ开发者_JAVA百科er "You have to store it to be able to dispose it": In my specific case, the TcpClient is usually living for a long time (app lifetime), so disposing it is not really a must. However, I agree that, in general, it has to be stored just to be able to call Dispose.
The NetworkStream will not be deleted if it's still referenced. The garbage collector only cleans up objects that are no longer referenced - it doesn't really know anything about the objects it has to collect, it just tracks references.
However, you may find that TcpClient has a finalizer that will invalidate the stream if the TcpClient is collected. It's probably safer to keep a reference to the TcpClient as well. (As far as I can see from the source code, the finalizer doesn't currently do this, but there's no guarantee that it won't in the future.)
If the object is not referenced, it will be garbage collected eventually, that will make your NetworkStream unusable. You need to keep the reference of that TcpClient object as long as you wish to use it.
精彩评论