Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TaskFactory.StartNew versus ThreadPool.QueueUserWorkItem

Tags:

Apparently the TaskFactory.StartNew method in .NET 4.0 is intended as a replacement for ThreadPool.QueueUserWorkItem (according to this post, anyway). My question is simple: does anyone know why?

Does TaskFactory.StartNew have better performance? Does it use less memory? Or is it mainly for the additional functionality provided by the Task class? In the latter case, does StartNew possibly have worse performance than QueueUserWorkItem?

It seems to me that StartNew would actually potentially use more memory than QueueUserWorkItem, since it returns a Task object with every call and I would expect that to result in more memory allocation.

In any case, I'm interested to know which is more appropriate for a high-performance scenario.

like image 969
Dan Tao Avatar asked Jun 15 '10 16:06

Dan Tao


People also ask

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 Threadpool QueueUserWorkItem?

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 task run () and Taskfactory StartNew () methods?

Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!

Does TPL use Threadpool?

Thread-Pool pattern states, the work items are queued and the free threads in thread pool takes one from this queue. TPL however store the items (tasks) to queues of threads and work-stealing works if needed...


1 Answers

Performance is a ... depends. If you are doing a lot of parallel tasks, then .net 4 tasks will perform better, plus give you more fine grained control (more robust cancellation, ability to wait on multiple tasks simultaneously, ability to create parent/child task relationships, Ability to specify LongRunning, etc.. etc.. etc..)

Additionally, the ability to specify your own TaskScheduler means you can customize it for your needs. The built-in task scheduler is far more multi-core aware than the old ThreadPool.

As for using more memory. Every thread reserves a minimum of 1MB of memory, the tiny amount used to store a task object is inconsequential. I really would think that's the last of your worries.

like image 191
Erik Funkenbusch Avatar answered Sep 23 '22 11:09

Erik Funkenbusch