13

I have a singleton that has a running thread for obtaining records from a server. But when I stop my winform application the thread keeps running. I have tried to create a destructor in my singleton to abort the thread if it running, but it does not have any effect on the thread - I know that the destructor is being evoked.

I am looking for suggestions on how I should shut down a thread when my application closes. thanks

C#, .net2

fishhead
  • 5,829
  • 7
  • 32
  • 43
  • possible duplicate of [How to stop BackgroundWorker on Form's Closing event?](http://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event) – Hans Passant Aug 22 '10 at 15:43
  • I looked at your link sugestion...it didn't do a thing for me – fishhead Aug 22 '10 at 15:46

2 Answers2

73

A thread can be:

  • Foreground : will keep alive your programs until it is finish.
  • Background : will be terminated when you close your application.

When you create a thread, it is by default a foreground thread.

You can change that like this:

Thread t = new Thread(myAction);
t.IsBackground = true;
t.Start();
didier
  • 811
  • 6
  • 4
  • Does a background thread end when a form is closed? For example, say I have multiple forms and in one form I have a thread. When the form closes, will the thread terminate as well even if it is in an infinite loop? Or will the thread end when application exits (when Main finishes processing)? – JT9 Oct 28 '15 at 14:56
  • 1
    @JT9 I just tested it, background thread does Not end when a form is closed in a multi-form application. – tunafish24 Jul 14 '16 at 08:24
  • What if the thread is used on the main/startup form? – Yakov .P Jan 01 '21 at 16:31
10

The best option, if possible in your application, is cooperative cancellation.

A thread automatically stops when it has no more code to execute. So, when the user closes your application, you set a flag indicating that your thread should stop. The thread needs to check from time to time if the flag is set and, if so, stop obtaining records from the server and return.

Otherwise, you can roll your own solution, for example

static bool isCancellationRequested = false;
static object gate = new object();

// request cancellation
lock (gate)
{
    isCancellationRequested = true;
}

// thread
for (int i = 0; i < 100000; i++)
{
    // simulating work
    Thread.SpinWait(5000000);

    lock (gate)
    {
        if (isCancellationRequested)
        {
            // perform cleanup if necessary
            //...
            // terminate the operation
            break;
        }
    }
}
dtb
  • 213,145
  • 36
  • 401
  • 431