C# CA2000和返回的套接字对象:如何解决?
我有下一个功能:C# CA2000和返回的套接字对象:如何解决?,c#,sockets,code-analysis,idisposable,ca2000,C#,Sockets,Code Analysis,Idisposable,Ca2000,我有下一个功能: public static Socket ConnectSocket(string srvName, int srvPort) { Socket tempSocket = null; IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry(srvName); //// Loo
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
如何解决此问题?如果某个对象抛出异常,您既不返回套接字,也不关闭它 尝试:
如果有东西抛出异常,您既不返回套接字也不关闭它 尝试:
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;
}