• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1121
  • Last Modified:

Disposing of Socket

I am using a socket (System.Net.Sockets.TcpClient) to send a message.  When I finish sending the message, I want to properly dispose of the socket.

Below is what I have:

            Dim client As System.Net.Sockets.TcpClient
            client = New System.Net.Sockets.TcpClient

            client.Connect (IPAddress, Port)

            networkStream = client.GetStream()

            networkStream.Write(Data, 0, Data.Length)

            networkStream = Nothing

            client = Nothing

Is this the correct way to dispose of the socket, or am I missing something?  There is not a .Dispose method on a TcpClient object, so close is the closest thing I have.  Is disposing of the stream and then closing the socket all that is needed, or should I be doing something else?
2 Solutions
I think because of the special natuer of socket object the close will mark for dispose but after running all object cleanup ( tcpclient has  a protected methods for dispose and finalize)
so yes close is enough

this is from Microsoft documintation

The Close method marks the instance as disposed and requests that the associated Socket close the TCP connection
Setting the object usually marks the object for cleanup. The Garbage Collector in CLR automatically disposes all objects which are not referenced anymore (setting to nothing dereferences it).
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now