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?
shutdownNow() should be used to shutdown the thread pool to gracefully exiting the application.
Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.
QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
A thread pool is - as the name suggests - a pool of worker threads which are always running. Those threads then normally take tasks from a list, execute them, then try to take the next task. If there's no task, the thread will wait.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With