c# GUI挂起,但仍然可以监听和处理



为什么我的c#服务器GUI挂起?知道我哪里做错了吗?谢谢你

它就像,当我点击button1的那一刻,GUI挂起,但它仍然可以处理请求,监听和接受传入的客户端连接。

    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    TcpListener listener = null;
    TcpClient client = null;
    NetworkStream stream = null;
    BinaryWriter writer = null;
    BinaryReader reader = null;
    string vouchercode;
    string username;
    string password;
    string reseller;
    string fresh;
    string result;

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            listener = new TcpListener(new IPAddress(new byte[] {127,0,0,1}), 6666);
            listener.Start();
            while (true)
            {
                label1.Text = "waiting....";
                using (client = listener.AcceptTcpClient())
                {
                    label1.Text = "Connection request accepted!";
                    using (stream = client.GetStream())
                    {

                        //some codes here ..
                    }
                }
            }
        }

        catch (WebException ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (listener != null) listener.Stop();
            if (writer != null) writer.Close();
            if (reader != null) reader.Close();
        }

    }

}

}

它挂起,因为AcceptTcpClient()是一个阻塞方法。您可以查看并尝试合并BeginAcceptTcpClient()以使其无阻塞。在msdn页面中有一个示例

当您在UI线程上进行处理时(就像您在按钮单击处理程序中一样),重要的是不要阻塞。正如Bala所指出的,你有一个阻塞调用,它处于一个(可能是无限的)循环中,这是一个问题,因为你永远不会从函数中返回,允许窗口消息被处理(窗口消息做一些事情,如重新绘制窗口,响应UI控件,如按钮点击,等等…)。

答案是要么使button1_Click非阻塞,要么将套接字代码移动到不同的线程。

查看这个SO线程:

如何在。net中扩展tcplistener传入连接?

您还进入了没有逻辑的while循环,我可以看到退出它。所以你会被绞死。将繁重的工作从事件中剥离出来,在这种情况下转移到不同的线程中,这也是一个很好的实践。

最新更新