Reputation: 40032
I am just learning about the new Threading and Parallel libraries in .Net 4
In the past I would create a new Thread like so (as an example):
DataInThread = new Thread(new ThreadStart(ThreadProcedure));
DataInThread.IsBackground = true;
DataInThread.Start();
Now I can do:
Task t = Task.Factory.StartNew(() =>
{
ThreadProcedure();
});
What is the difference if any?
Thanks
Upvotes: 111
Views: 111243
Reputation: 1937
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
Upvotes: 13
Reputation: 812
Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.
Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.
This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.
Upvotes: 1
Reputation: 2489
There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.
If you have a long running background work you should specify this by using the correct Task Option.
You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.
Upvotes: 84
Reputation: 1500525
The task gives you all the goodness of the task API:
Task.ContinueWith
)Note that in both cases you can make your code slightly simpler with method group conversions:
DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);
Upvotes: 77