The objective of the Tasks namespace is to provide a pluggable architecture to make multi-tasking applications easier to write and more flexible.
The implementation uses a TaskScheduler
object to control the handling of tasks. This has virtual methods that you can override to create your own task handling. Methods include for instance
protected virtual void QueueTask(Task task)
public virtual int MaximumConcurrencyLevel
There will be a tiny overhead to using the default implementation as there's a wrapper around the .NET threads implementation, but I'd not expect it to be huge.
There is a (draft) implementation of a custom TaskScheduler that implements multiple tasks on a single thread here.
In computer science terms, a Task
is a future or a promise. (Some people use those two terms synonymously, some use them differently, nobody can agree on a precise definition.) Basically, a Task<T>
"promises" to return you a T
, but not right now honey, I'm kinda busy, why don't you come back later?
A Thread
is a way of fulfilling that promise. But not every Task
needs a brand-new Thread
. (In fact, creating a thread is often undesirable, because doing so is much more expensive than re-using an existing thread from the thread pool. More on that in a moment.) If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread to sit around and wait for the data when it can be servicing other requests. Instead, the Task
might register a callback to receive the value(s) when they're ready.
In particular, the Task
does not say why it is that it takes such a long time to return the value. It might be that it takes a long time to compute, or it might be that it takes a long time to fetch. Only in the former case would you use a Thread
to run a Task
. (In .NET, threads are freaking expensive, so you generally want to avoid them as much as possible and really only use them if you want to run multiple heavy computations on multiple CPUs. For example, in Windows, a thread weighs 12 KiByte (I think), in Linux, a thread weighs as little as 4 KiByte, in Erlang/BEAM even just 400 Byte. In .NET, it's 1 MiByte!)
Best Answer
Task
is an order to program to do something in asynchronous way. TheThread
is actuallyOS
kernel object which executes what was requested. Think aboutTask
like a clever thread aggregator/organizer that "knows" how much task is better to run contemporary on yourCPU
. It's just cleverer then common implementations of multi-threading (that's why it's suggested choice from Microsoft). It's a feature that helps you managingThreads
in easier way.Look also on this Should i use ThreadPools or Task Parallel Library for IO-bound operations that may give you some hints on performance issues you may be interested in.