2013-02-14 5 views
0

У меня есть следующая функция:CA2000 и возвращенный объект Socket: как решить?

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.

Как это решить?

ответ

3

Если что-то порождает исключение, вы не возвращаете розетку или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; 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^