C# - 异步 TcpClient 连接的内存释放

C# - Memory release for an asynchronous TcpClient Connection

我正在尝试创建一个异步方法来验证我是否可以通过 TCP 连接主机。好像我没有正确释放我使用的所有内存。

我是不是忘记了什么?

我的连接指示器是:

Bool CanConnectToHost = false;

我的职能是:

    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
        } 
    }

非常感谢

  1. 我认为你不需要关心这里的内存。您可能会观察到,垃圾收集不会在您的方法完成后立即清理所有内存。它最终会在有时间或您的进程开始运行可用内存不足时这样做。

  2. 如果无法建立连接,
  3. TcpClient.ConnectAsync() 将抛出 SocketException。所以你的代码有一个缺陷,在这种情况下,你没有正确设置你的 CanConnectToHost (尽管它是 false 通过初始化)。
    我建议在这里使用 using 。这还有一个好处,即 Close() 也会在出现异常时被调用。并且 Close() 还将立即释放 TcpClient 使用的所有资源,而不仅仅是当 GC 开始工作时。

你的代码 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;
    } 
}