【发布时间】: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