Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# CA2000和返回的套接字对象:如何解决?_C#_Sockets_Code Analysis_Idisposable_Ca2000 - Fatal编程技术网

C# CA2000和返回的套接字对象:如何解决?

C# CA2000和返回的套接字对象:如何解决?,c#,sockets,code-analysis,idisposable,ca2000,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); //// Loo

我有下一个功能:

    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


如何解决此问题?

如果某个对象抛出异常,您既不返回套接字,也不关闭它

尝试:


如果有东西抛出异常,您既不返回套接字也不关闭它

尝试:

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