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(()=>{....}))
?
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
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:
Using Task.Run
or Task.Factory.StartNew
without any flags - This will queue work on the .NET ThreadPool, as stated.
Using Task.Factory.StartNew
and specifying the TaskCreationOptions.LongRunning
- This will signal the TaskScheduler
to use a new thread instead of a ThreadPool thread.
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.
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.
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