我有下一个功能:
public static Socket ConnectSocket(string srvName, int srvPort)
{
Socket tempSocket = null;
IPHostEntry hostEntry = null;
try
{
hostEntry = Dns.GetHostEntry(srvName);
//// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
//// an exception that occurs when the host IP Address is not compatible with the address family
//// (typical in the IPv6 case).
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, srvPort);
if (!ipe.AddressFamily.Equals(AddressFamily.InterNetwork))
continue;
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
return tempSocket;
}
tempSocket.Close();
}
throw new ConnectionThruAddressFamilyFailedException();
}
finally
{
//I can't close socket here because I want to use it next
}
}
在这里的代码分析过程中,我显然有CA2000(在失去作用域之前处理对象)警告。返回的套接字接下来用于和服务器通信。所以我不能在这里处理它。即使我稍后在这里处理这个对象,我也有CA2000。
如何解决这个问题?
如果有东西抛出异常,您既不返回套接字也不返回Close
/Dispose
it。
尝试:
try
{
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream,
ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
return tempSocket;
}
tempSocket.Close();
tempSocket = null;
}
catch (Exception)
{
if (tempSocket != null)
tempSocket.Close();
throw;
}