Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating threads - Task.Factory.StartNew vs new Thread()

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

like image 772
Jon Avatar asked Oct 25 '11 13:10

Jon


People also ask

What is the difference between task run and task factory StartNew?

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!

What does task factory StartNew do?

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.

Does task create a new thread C#?

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 .

How to Start new thread in c#?

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.


1 Answers

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.

like image 192
sanosdole Avatar answered Sep 23 '22 00:09

sanosdole