Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does TcpClient.Dispose() closes the TcpClient.GetStream?

Tags:

c#

sockets

For closing a TcpClient it's necessary to close the stream. And the usual way of doing that is:

        client.GetStream().Close();
        client.Close();

so using client.Close() by itself is not enough, my question is does the client.Dispose() works same as client.GetStream().Close() so the closing will be like

        client.Dispose();
        client.Close();

this is what i understood from reading the TcpClient reference source as the Dispose method closes the stream, so am i correct or am i missing something? Thank you in advanced.

like image 977
vkr02692 Avatar asked Dec 19 '22 21:12

vkr02692


1 Answers

Close calls Dispose, Dispose disposes the stream:

IDisposable dataStream = m_DataStream;
if (dataStream != null)
{
    dataStream.Dispose();
}

You don't need to call both Close and Dispose. Choose one.

You can check the source code

It's quite common for IDisposable classes to have another method doing the same as Dispose, but with a different, domain-specific name. Very often IDisposable.Dispose is implemented explicitly, so that it can be used by using statement or after a cast, but doesn't clutter the class' interface.

like image 158
Jakub Lortz Avatar answered Jan 11 '23 06:01

Jakub Lortz