How to close a thread

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sidra Nisar
    New Member
    • Feb 2010
    • 17

    How to close a thread

    Hi.
    In my program, I'm initiating a thread in (console application) by getting a signal from my client(windowsf orm)who hits a connect button and it works the way i want.....
    Now i am trying to close this thread when my client clicks on the disconnect button but i'm unable to find a way.

    Kindly suggest what should be done to close the thread and terminate the form.

    Here is the code I tried

    Code:
    //declaring a flag to keep a check on when the user hits disconnect
    
    public int flag = 0;
    
    //to start a thread  
    
    private void button2_Click(object sender, EventArgs e)
            {
                readData = "Connected to Chat Server ...";
                msg();
                clientSocket.Connect("192.168.1.7", 5060);
                serverStream = clientSocket.GetStream();
    
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$" + textBox4.Text + "%");
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
    
                Thread ctThread = new Thread(getMessage);
                ctThread.Start();
           if (flag == 10)
    {
    ctThread.Abort();
    }
            }
    
    // other processes
    
    // When the client hits diconnect
    
      private void button3_Click_1(object sender, EventArgs e)
            {
                readData = "You have left the session";
                msg();
    
             // here i want to close the respective thread
        
    flag = 10;
            }
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    The simplest way would be to declare ctThread as a private variable, assign it in button2_Click() and call it's Abort()-method in button3_Click_1 ()

    e.g.
    Code:
    class xy {
      Thread ctThread = null;
    
      private void button2_Click(object sender, EventArgs e) {
       // ...
       ctThread = new Thread(getMessage);
       ctThread.Start();
       // ...
      }
    
    private void button3_Click_1(object sender, EventArgs e) {
       // ...
       if(ctThread != null)
         ctThread.Abort();
       // ...
      }
    }

    Comment

    • Sidra Nisar
      New Member
      • Feb 2010
      • 17

      #3
      Thank you very much. It worked for me.

      Comment

      Working...