0

我有下一个功能:

    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。

如何解决这个问题?

4

1 回答 1

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;
}
于 2013-02-14T09:30:31.143 回答