Last days I try learning about Multitasking in .NET. I have few question about this. First of all. I know that in .NET exist thing who's name is "ThreadPool", so if we create new thread with Thread class we using thread from ThreadPool or create new one?
What about Task library. In the msdn we can read: "Represents an asynchronous operation." but create new thread and using asynchronous are two different ways, right? So if we using Task library we create async operations or create new thread?
If yes so when we should to using async/await keywords? Where is the difference betweent above approach?
Lets try and break each question:
so if we create new thread with Thread class we using thread from ThreadPool or create new one?
The ThreadPool
does what its name indicates, it is a pool of threads. When you use the Thread
class, you're creating a new Thread, unrelated to these that exist in the ThreadPool
.
In the msdn we can read: "Represents an asynchronous operation." but create new thread and using asynchronous are two different ways, right?
Right. Doing an asynchronous operation doesn't mean "create a new thread and work on that thread". I mean, that is doing things in parallel. Asynchronous operations usually require no extra threads in the process at all, they are naturally asynchronous all the way down to the OS.
So if we using Task library we create async operations or create new thread?
You can do both:
Promise-style tasks - These play along together nicely with the async-await
operators introduced in C# 5. They represent asynchronous operations which require no threads to be used. An example of these can be found in various BCL classes, such a the Stream
classes, HttpClient
, etc. Notice that most of the classes doing I/O bound operations use promise style task.
Using Task.Run
or Task.Factory.StartNew
. This will take a ThreadPool
thread and execute the provided delegate inside unless you explicitly tell it you want it to create a new Thread using TaskCreationOptions.LongRunning
.
If yes so when we should to using async/await keywords?
async-await
goes along with anything that is an awaitable
. An awaitable
is any class/struct that has a GetAwaiter
method, which return a type that implements INotifyCompletion
or ICriticalNotifyCompletion
interface. You can read more about async-await
here
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