views:

63

answers:

2

Hello, 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

+4  A: 

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
+2  A: 

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