【问题标题】:C# - Memory release for an asynchronous TcpClient ConnectionC# - 异步 TcpClient 连接的内存释放
【发布时间】:2017-05-20 09:56:34
【问题描述】:

我正在尝试创建一个异步方法来验证我是否可以通过 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
        } 
    }

非常感谢

【问题讨论】:

  • 为什么你认为你没有释放所有资源?顺便提一句。更好的方法是 using 语句` using(TcpClient client = new TcpClient()) { ..... }` 你不需要调用client.Close(),如果发生异常它也会关闭客户端。跨度>

标签: c# asynchronous memory-management connection tcpclient


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

  2. 如果无法建立连接,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;
    } 
}

【讨论】:

    猜你喜欢
    • 2020-11-26
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多