Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do each new System.Threading.Tasks.Task() creates a new thread?

I was just trying to figure out as I am using Task object for to have my time taking operation runs in a separate channel. But I wonder do Task(()=>{...}) is it similar to create new Thread(new ThreadStart(()=>{....})) ?

like image 945
BreakHead Avatar asked Feb 12 '23 04:02

BreakHead


2 Answers

Short answer: No. Tasks are executed via a thread pool. Here'r a blog about this: Threads vs. Tasks: A task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool

like image 114
Matt Avatar answered Feb 14 '23 16:02

Matt


A Task represents a promise of work to be completed some time in the future.

There are a couple of options to how a Task gets created:

  1. Using Task.Run or Task.Factory.StartNew without any flags - This will queue work on the .NET ThreadPool, as stated.

  2. Using Task.Factory.StartNew and specifying the TaskCreationOptions.LongRunning - This will signal the TaskScheduler to use a new thread instead of a ThreadPool thread.

  3. When using async-await feature of C#-5, also known as Promise Tasks. When you await on a method returning a Task or a Task<T>, they may not use any threading mechanism, either ThreadPool or new Thread to do their work as they may use a purely asynchronous API, meaning they will continue to execute on the thread which executed them, and will yield control back to calling method once hitting the firstawait keyword.

  4. Thanks to Servy for this one. Another options for execution is creating a custom TaskScheduler and passing it to Task.Factory.StartNew. A custom TaskScheduler will give you fine-grained control over the execution of your Task

All these options come to show that a Task is merely a promise, and there are many forms in which you may fulfill that promise. A Thread is a means to an end, while a Task is the unit of work we want done.

like image 28
Yuval Itzchakov Avatar answered Feb 14 '23 18:02

Yuval Itzchakov