Hi, is there a way to abort threads created with QueueUserWorkItem?
Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?
Hi, is there a way to abort threads created with QueueUserWorkItem?
Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?
Yes, they will. However, if you are using unmanaged resources in those threads, you may end up in a lot of trouble.
You don't need to abort them. When your application exits, .NET will kill any threads with IsBackground = true. The .NET threadpool has all its threads set to IsBackground = true, so you don't have to worry about it.
Now if you're creating threads by newing up the Thread class, then you'll either need to abort them or set their IsBackground property to true.
The threadpool uses background threads. Hence, they will all be closed automatically when the application exits.
If you want to abort a thread yourself, you'll have to either manage the thread yourself (so you can call Thread.Abort() on the thread object) or you will have to set up some form of notification mechanism which will let you tell the thread that it should abort itself.
However, if you are using unmanaged resources in those threads, you may end up in a lot of trouble.
That would rather depend how you were using them - if these unmanaged resources were properly wrapped then they'd be dealt with by their wrapper finalization regardless of the mechanism used to kill threads which had referenced them. And unmanaged resources are freed up by the OS when an app exits anyway.
There is a general feeling that (Windows) applications spend much too much time trying to clean-up on app shutdown - often involving paging-in huge amounts of memory just so that it can be discarded again (or paging-in code which runs around freeing unmangaged objects which the OS would deal with anyway).
yeah, they are background, but f.ex if you have application where you use ThreadPool for some kinda multiple downloading or stuff, and you want to stop them, how do you stop ? my suggestion would be: exit thread asap, f.ex
bool stop = false;
void doDownloadWork(object s)
{
if (!stop)
{
DownloadLink((String)s, location);
}
}
and if you set stop = true, second (currently in queue) threads automatically exit, after queue threads finishes it process.
According to Lukas Šalkauskas' answer.
But you should use:
volatile bool stop = false;
to tell the compiler this variable is used by several threads.