[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1043
  • 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.Flush()

            networkStream.Dispose()
            networkStream = Nothing

            client.Close()
            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?
0
Ignyte_Software
Asked:
Ignyte_Software
2 Solutions
 
FarWestCommented:
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
0
 
CodeCruiserCommented:
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).
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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