Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort threads created with ThreadPool.QueueUserWorkItem

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?

like image 782
juan Avatar asked Aug 25 '08 20:08

juan


People also ask

How do you stop threading in a ThreadPool?

shutdownNow() should be used to shutdown the thread pool to gracefully exiting the application.

When should you not use ThreadPool?

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.

What is the use of ThreadPool QueueUserWorkItem method?

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.

What is the difference between thread and ThreadPool?

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.


2 Answers

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.

like image 70
Judah Gabriel Himango Avatar answered Oct 15 '22 07:10

Judah Gabriel Himango


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).

like image 20
Will Dean Avatar answered Oct 15 '22 07:10

Will Dean