开发者

c# gui hangs but still can listen and process

why is that my c# server gui hangs? any idea where did i go wrong? thank you

its like, the moment i click the button1, the gui hangs, but it can still process requests and listen and accept for incoming client connections.

开发者_如何学编程    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();
        }


    }



}

}


It hangs because AcceptTcpClient() is a blocking method. You can look into and try incorporating BeginAcceptTcpClient() for it to be non-blocking. There is an example in the msdn page.


When you are doing processing on the UI thread (like you are in the button click handler), it's important not to block. As Bala pointed out, you have a blocking call which is sitting in a (possibly infinite) loop, and this is a problem because you never return out of the function, allowing window messages to be processed (window messages do things like repainting windows, respond to UI controls like button clicks, etc...).

The answer is to either make button1_Click non-blocking, or move the sockets code to a different thread.

Check out this SO thread:

How to spread tcplistener incoming connections over threads in .NET?


You are also entering a while loop with no logic that I can see to exit it. So you are going to hang. It is also always good practice to get your heavy lifting out of your events and in this case into a different thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜