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
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!
StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.
Note: Just using a Task in . NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the .
The following code snippet shows how you can create a new thread object using this delegate. Thread t = new Thread(new ThreadStart(MyThreadMethod)); To start the newly created thread, you should call the Start method on the thread object you have created.
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.
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