سؤال

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