Reputation: 7059
My Understading:
Async is different from threading. In Async, we use a single thread and can run multiple tasks from that. In .Net framework
, we have a thread pool which allocate a new thread on every new http web request. So every request is handled by a single thread. However, IIS
do not have it's own threadpool, it uses CLR's threadpool.
If we create any new additional thread in our web request, then we loses one thread from threadpool and if your site has lots of traffic then your site users have to wait until any thread gets free. So better to use asyncronous tasks in ASP.Net apps. Async tasks will be executed in single thread in which our main web request is executing.
How async works. Suppose we create two independent/async tasks in a controller, suppose they are T1 and T2. T1 executes for some time interval and then T2. Then again main web request. They use CPU by using time slicing.
Web Request -----> Single Thread Pool Thread (Main Request + T1 +T2)
=>
Execution Lifecycle --> [Main request, T1, T2, T1, Main Request, T2, T1.....]
and if we use await Task.WhenAll
then our main thread is released and given back to thread pool and once all tasks completes we are given
our thread back to continue.
First , clear my concepts if I am wrong any where?
Then I have few confusions:
Upvotes: 2
Views: 1046
Reputation: 456537
They use CPU by using time slicing.
Here's where you're wrong. Threads share a CPU via time slicing. Tasks are quite different.
There are two kinds of tasks: Delegate Tasks and Promise Tasks. Delegate Tasks will execute on a thread - they actually have code to run, so they have to use up CPU. However, Delegate Tasks are extremely rare in asynchronous code, and in general should not be used on ASP.NET.
Promise Tasks are what the vast majority of asynchronous code uses. Promise Tasks just represent some kind of "completion". For the vast majority of their work, they do not execute code, and do not require a CPU. For more information on how this is possible, see my blog post There Is No Thread.
if our thread is given to threadpool then which thread will work upon tasks which are in WhenAll.
No thread is necessary. That's the whole point of using asynchronous code on ASP.NET.
Are we given the same thread back after WhenAll completes or we are given randomly a new thread?
It is a thread from the thread pool, which may or may not be the same one that you started on. For this reason, using [ThreadStatic]
and the like will cause problems.
For more information about how async works, I recommend reading my async intro and my article on async ASP.NET. For more about the two types of task, I recommend reading my Task overview and Task status blog posts.
Upvotes: 9