Exiting Threads

You can use the Thread.Abort() method to kill a thread. This throws a ThreadAbort-Exception. The problem with this is that you do not know where exactly your program stops executing. It could be in the middle of an important calculation that makes a proper resource cleanup impossible. A more proper way would include a shared variable. By testing that variable you can exit your thread at predefined code positions.

private class parameters {
  //public double a;
  //public string s;
  public bool exitFlag = false;

static private void myThread(object xParameters) {
  parameters p = xParameters as parameters;
  int i = 0;
  while (!p.exitFlag) {
    Console.WriteLine("thread loop number " + i++);
  Console.WriteLine("good bye!");
} //

static void Main(string[] args) {
  Thread t = new Thread(new ParameterizedThreadStart(myThread));
  t.IsBackground = true;
  t.Name = "MyBackgroundThread";
  t.Priority = ThreadPriority.Normal;
  parameters p = new parameters();

  Console.WriteLine("press return to exit the program");

  p.exitFlag = true;
} //

You can use a global static boolean to shut down a thread, but I think you will appreciate my solution using parameters as you can then reuse standard parameter interfaces and make your code more generic. You surely don’t want to deal with global variables when you have 100 threads running.

Exiting your application

In Windows.Forms applications you can use Application.Exit().  This method  terminates all message loops and closes all windows. You can eg. execute your cleanup code in the Form.OnClose events.
This method does not terminate your threads. If you do not deal with all your Foreground threads properly, then these threads  keep running. Therefore you must take measures to kill your threads.

The Environment.Exit() method is not part of Windows.Forms. It kills the process. Unsaved changes in forms may get lost. Again, you have to clean up properly and free resources.


About Bastian M.K. Ohta

Happiness only real when shared.

Posted on December 3, 2013, in Basic, C#, Threading and tagged , , , , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: