简体   繁体   English

测试Tcp连接错误的线程

[英]Thread to test Tcp Connection Error Occur

I try to test Socket Connection. 我尝试测试套接字连接。 It show error 显示错误

Cannot access a disposed object. 无法访问已处置的对象。 Object name: 'System.Net.Sockets.TcpClient'. 对象名称:“ System.Net.Sockets.TcpClient”。

at Connect(ip,port). 在Connect(ip,port)。

       System.Net.Sockets.TcpClient client = new TcpClient();
        try
        {
            System.Threading.Thread t = new System.Threading.Thread(() =>
        {
            client.Connect(ip,port );

        });
            t.Start();
        }
        catch (SocketException ex)
        {


        }
        catch (Exception ex) {

        }
        finally
        {
            client.Close();
        }

This is a race condition between the thread you start here: 这是您在此处启动的线程之间的竞争条件:

    System.Threading.Thread t = new System.Threading.Thread(() =>
    {

        client.Connect(ip,port );

    });
    t.Start();

and the finally block here: 最后的块在这里:

    finally
    {
        client.Close();
    }

In this case the main thread reached the finally block before your connection was finished. 在这种情况下,主线程在连接完成之前到达了finally块。

Object creation and clean up really should be on the same thread, so try something like this unless you really need the closure. 对象的创建和清理实际上应该在同一线程上,因此,除非确实需要关闭,否则请尝试这样的操作。

System.Threading.Thread t = new System.Threading.Thread(() =>
{
    using(TcpClient client = new TcpClient())
    {
        client.Connect(ip, port);
        //followup code here
    }

});
t.Start();

depending on what you are trying to achieve, you can modify the code to 根据您要实现的目标,可以将代码修改为

System.Threading.Thread t = new System.Threading.Thread(() =>
                {
                    using (System.Net.Sockets.TcpClient client = new TcpClient())
                    {
                        client.Connect("127.0.0.1", 80);
                        // Communicate with the Server. 
                    }   // The client object would be disposed here
                });
                t.Start();

Remember this code would create a new instance of TcpClient each time the thread would run. 记住,每次线程运行时,此代码都会创建一个新的TcpClient实例。 I am assuming, you would communicate with the server soon after establishing the connection and can then safely dispose the object, once its done. 我假设,您将在建立连接后立即与服务器通信,一旦完成,便可以安全地处置该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM