Program doesn't Terminate

I've made a program that has a thread that continuously receives the bytes from a server via socket.
The code is like this:

data = new byte[1024];
receiverThread = new Thread(new ThreadStart(Rec));
receiverThread.Start();
public void Rec()
  {
   while(true)
   {
    try
    {
     recv = client.ReceiveFrom(data, ref remoteEP);
     txtDisplay.Text += Encoding.ASCII.GetString(data, 0, recv) + "\r\n" ;   
/*txtDisplay is the Textbox in which the received strings are displayed  */
    }
    catch(Exception ex)
    {
     MessageBox.Show(ex.ToString());
     break;
    }
   }
  }
Now the problem is even when I close the main form, the program doesn't terminate. The program gets stuck in the code i've marked with the red.
So please can anybody can tell me, what can I do to completely terminate the program



Answer this question

Program doesn't Terminate

  • Feras

    Did you close the socket This should force the ReceiveFrom() method to return allowing the thread to terminate (yes, you need to terminate the thread first). E.g:

    receiverThread.Abort();

    client.Close();

    Well, it worked for me anyway.



  • GoffQ

    I had already tried that. That doesn't work.

  • Maxon

    well you can use environment.exit(0) method to free all the resources hooked up in your application.
    You can use this method in and form closing event

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    environment.exit(0);
    }
    this might not be the effective one to implement but it can be helpful to you

  • gorovvv

     Konstantin Gonikman wrote:
    Hmm... tried to kill the thread with receiverThread.Abort() on program exit

    Try receiverThread.Interrupt() instead.

  • ChuckH

    You have an endless loop!  Your while doesn't seem to want to exit.  What happens when the ReceiveFrom method does not return any data   Do you check for that   Something like this:

    if (recv == string.Empty)
       break;

    You need something to break out of the while loop.

  • tris111

    Not pretty, but its a killer.

    System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();

    process.Kill();



  • Neo

    Hmm... tried to kill the thread with receiverThread.Abort() on program exit

  • Scott_Morrison

    It might be your loop like he said but also said Thread.Background = true so the thread quits when the form closes.
  • Heidi8139

    Thanks KyleB,
    That helps.

  • Program doesn't Terminate