Difference between Thread, Task and async / await topics
I have been trying to learn about multitasking in .NET in recent days. I have few questions about this. First of all. I know there is an item in .NET called "ThreadPool", so if we create a new thread using the Thread class, do we use the thread from the ThreadPool, or create a new one?
How about a task library. In msdn we can read: "Represents an asynchronous operation". but creating a new thread and using asynchronous are two different ways, right? So if we are using a task library, are we creating async operations or are we creating a new thread?
If so, when should we use the async / await keywords? Where is the difference between the approaches above?
source to share
Let's try to break down each question:
so if we create a new thread with class Thread, do we use the thread from ThreadPool or create a new one?
ThreadPool
does what its name indicates, it's a thread pool. When you use a class Thread
, you create a new thread that is not related to those that exist in ThreadPool
.
In msdn we can read: "Represents an asynchronous operation". but creating a new thread and using asynchronous are two different ways, right?
Right. Performing an asynchronous operation does not mean "create a new thread and work on that thread". I mean I am doing things in parallel. Asynchronous operations usually do not require any additional threads in the process, they are naturally asynchronous right down to the OS itself.
So if we are using a task library, are we creating asynchronous operations or are we creating a new thread?
You can do both:
-
Promise-style tasks - they are well represented by
async-await
operatorsasync-await
in C # 5. They are asynchronous operations that do not require the use of threads. An example of this can be found in various BCL classes such as classesStream
,HttpClient
etc. Note that most of theHttpClient
/ inference- related classes use a promise style task. -
Using
Task.Run
orTask.Factory.StartNew
. This will take the threadThreadPool
and execute the provided delegate internally, unless you explicitly tell it you want to create a new oneTaskCreationOptions.LongRunning
withTaskCreationOptions.LongRunning
.
If so, when should we use the async / await keywords?
async-await
consistent with everything that is awaitable
. awaitable
is any class / structure that has a method GetAwaiter
that returns a type that implements an interface INotifyCompletion
or ICriticalNotifyCompletion
. You can read more about async-await
here
source to share