0

I have thread with while(true) which maintain my connection with client. Inside I have if with bool. When I click button it set "true" and file transfering is started (all instruction is in if).

My question is, how I could maintain connection in thread without while, or how I should go out that "while" when my client is disconnected.

public void SayHi()
        {
            try
            {
                while (true)//for maintain connection
                {

                    if(form1.transfer)
                    {
                        NetworkStream networkStream = clientSocket.GetStream();


                        CardNumber++;
                        form1.SendQuestion(clientSocket, CardNumber, Convert.ToInt32(clNo));

                        form1.transfer = false;
                        Thread AnswerThread = new Thread(WaitForAnswer);
                        AnswerThread.IsBackground = true;
                        AnswerThread.Start();
                    }
                }

            }
Henrik
  • 23,186
  • 6
  • 42
  • 92
Błażej
  • 3,617
  • 7
  • 35
  • 62

2 Answers2

0

Using while is not a very good idea as the CPU cycles are wasted spinning the loop.

If the SayHi() method is not in a separate thread, you could safely remove the while loop and directly call the SayHi() method from inside the button click event.

If the SayHi() method is in a separate thread, you can make use of a ManualResetEvent or an AutoResetEvent and use a WaitHandle to wait inside the while loop. This ensures that the CPU cycles are not wasted while the thread is not doing any task.

See the following link for example usage of WaitHandle: What is the basic concept behind WaitHandle?

Community
  • 1
  • 1
Anil Mathew
  • 2,590
  • 1
  • 15
  • 15
0

Use ManualResetEvent to synchornize threads. In backgroud thread use Wait and in button click answer use Set() method

Novakov
  • 3,055
  • 1
  • 16
  • 32