Search code examples
c#asynchronousmemory-managementconnectiontcpclient

C# - Memory release for an asynchronous TcpClient Connection


I am trying to create an asynchronous methode to verify if i can connect with an host Through TCP. It seem like i am not releasing correctly all the memory i use.

I'm i forgetting something ?

My Connection Indicator is :

Bool CanConnectToHost = false;

My Function is :

    private async void TryToConnectToHost()
    {
        // host IP Address and communication port
        string ipAddress = Properties.Settings.Default.HostIPaddr;
        int port = 9100;

        //Try to Connect with the host
        try
        {
            TcpClient client = new TcpClient();

            await client.ConnectAsync(ipAddress, port);

            //Verify if connected succesfully
            if (client.Connected)
            {
                //Connection with host
                CanConnectToHost = true;
            }
            else
            {
                // No connection with host
                CanConnectToHost = false;
            }

            //Close Connection
            client.Close();
        }
        catch (Exception exception)
        {
            //Do Something
        } 
    }

Thx a lot


Solution

    1. I don't think you need to care about memory here. What you probably observe is that the Garbage Collection doesn't bother to clean up all memory immediatly after your method is finished. It will do so eventually when it has time or your process starts to run out of free memory.

    2. TcpClient.ConnectAsync() throws a SocketException if the connection cannot be established. So your code has the flaw that in case of that exception, you don't set your CanConnectToHost correctly (though it is false by initialization).
      I recommend to use using here. That also has the advantage that Close() will also be called in case of the exception. And Close() will also free any resources used by the TcpClient immediatly and not only if GC starts to work.

    Your code with using:

    private async void TryToConnectToHost()
    {
        // host IP Address and communication port
        string ipAddress = Properties.Settings.Default.HostIPaddr;
        int port = 9100;
    
        //Try to Connect with the host
        try
        {
            using (TcpClient client = new TcpClient())
            {
                await client.ConnectAsync(ipAddress, port);
                CanConnectToHost = client.Connected; // no need for if
            }
        }
        catch (Exception exception)
        {
            CanConnectToHost = false;
        } 
    }