CA2000并返回Socket对象:如何解决?

时间:2013-02-14 09:19:47

标签: 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);

            //// 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 (Dispose objects before losing scope)警告。 返回的套接字接下来用于与服务器通信。所以我不能在这里处理它。即使我稍后在这里处理这个对象,我也有CA2000。

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

如果某些内容抛出异常,您既不会返回套接字也不会 Close / Dispose

尝试:

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