Disposing of Socket

Posted on 2011-10-05
Last Modified: 2012-05-12
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?
Question by:Ignyte_Software
    LVL 12

    Accepted Solution

    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
    LVL 83

    Assisted Solution

    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).

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
    A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
    This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    730 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now