How do I stop a thread when my winform application closes
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. than开发者_JAVA百科ks
C#, .net2
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();
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.
- As @Hans Passant noted, BackgroundWorker has built-in support for this.
- If you can upgrade, the .NET Framework 4.0 introduces a whole set of new classes that support cooperative cancellation of asynchronous operations.
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;
}
}
}
精彩评论