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
This question is related to
c#
.net
multithreading
.net-4.0
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:
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.
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);
Source: Stackoverflow.com