Starting a "new thread IsBackground = true "in Form2() and getting stuck in while(true) loop

113 Views Asked by At

I'm making a multithreaded chat server and chat client. The client has a Form1 called Login and a Form2 called MainProgram. The following code is from "Login". What I'm trying to do is transitioning from Login to MainProgram...

        MainProgram mP = new MainProgram(clientSocket, username);
        mP.Closed += (s, args) => this.Close();
        this.Hide();
        mP.ShowDialog();
        mP.Show();

... however. When assigning mP MainProgram mP = new MainProgram(clientSocket, username); The code get's stuck in the thread specified here:

public MainProgram(TcpClient c, string u)
    {
        InitializeComponent();
        try
        {
            serverStream = c.GetStream();
            clientSocket = c;
            username = u;
            new Thread(Receive()) { IsBackground = true }.Start();
        }

Here is the Thread:

        private ThreadStart Receive()
    {
        while (true)
        {
            try
            {
                byte[] inStream = new byte[1024];
                serverStream.Read(inStream, 0, inStream.Length);
                string returndata = Encoding.ASCII.GetString(inStream);
                returndata = returndata.Substring(0, returndata.IndexOf("$"));
                Msg($"{returndata}");
            }
            catch(Exception e)
            {
                MessageBox.Show($"{e.Message}\n\n{e.ToString()}");
            }
        }
    }

Please note that the thread is supposed to be running this while loop indefinitely, but in the background. Right now it doesn't make a new thread and runs on the MainThread. The problem is that i don't know how to start this thread without making the client get stuck in this while loop. And not transitioning.

1

There are 1 best solutions below

2
Kevin Gosse On BEST ANSWER

It seems you didn't understand what is ThreadStart. This is the signature of the method that is accepted to create a thread.

When you call:

new Thread(Receive()) 

You're actually calling the "Receive" method in the main thread, and giving its return value to the thread constructor (which never happens because it's stuck in your infinite loop.

Instead you need to do

new Thread(new ThreadStart(Receive))

Mind the removed parenthesis.

But then you'll get a compilation error because your Receive method doesn't have the right signature. So you need to change it into:

private void Receive()
{
    // ...
}