Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Thread Closing

Status
Not open for further replies.

Galarun

Programmer
Jun 28, 2005
24
0
0
US
Hello,

I have a program that runs threads for networking, and whenever I close it by pressing the X button in the top right corner the program threads still run, so I have to go to the task manager every time to close it. The only event I have is Server_Closing which is as follows:

private void Server_Closing(object sender, CancelEventArgs e)
{
this.Close();
Application.Exit();
}

Anyone have any suggestions on how to kill all running threads when the application closes so I don't have to go to the task manager every time? I need help!!!

-- Frustrated Programmer
 
You can do something like this

Code:
protected override void OnClosing(CancelEventArgs e)
    {
      // Declare a StackTrace
      System.Diagnostics.StackTrace O = new System.Diagnostics.StackTrace(true);
      
      // check to see why the window is closing
      System.Diagnostics.StackFrame F = O.GetFrame(7);
      
      // if the user ended the application (ALT-F4, clicking the corner X etc)
      if(F.GetMethod().Name == "DefWndProc")
      {
        // ... do all end stuff         
      }
    }

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Thanks for the reply, but I'm not too sure what you mean by "do all end stuff". How do I close the threads?
 
Apparently you are starting threads, leaving open connections, or terminating your application incorrectly.

Do you keep track of all the networking threads you open? and do you kill them properly?

If your Form opens/starts all the threads, then it should kill all the threads during the Server_Closing event.
 
Actually I'm not keeping track of my threads at all. I'm quite new to them and I'm still learning on how to handle them. Right now when I need to start a thread in a function I just make a new instance of Thread t and start it. I was under the impression that once the start function ended the thread would be terminated. Since I only run one extra thread at a time, should I just keep it as a global variable and terminate it when the Server_Closing function is called?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top