문제

I have next function:

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

And I obviously have CA2000 (Dispose objects before losing scope) warning during code analyse here. A returned socket next used to communicate with server. So I can't dispose it here. Even if I'm disposing this object later here I'm having CA2000.

How to solve this?

도움이 되었습니까?

해결책

If something throws an exception, you neither return the socket nor Close/Dispose it.

Try:

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top