I just would like to ensure I understood well the differences between async await and Task.run or Task.whenall
So async await is to process asynchronous methods. It means that there is an order of processing implied.
I run a long processing without blocking the main thread and I wait for the result to continue.
For Task.Run and Task.Whenall there is a new notion with multithreading. It means that I can launch a long process on a new thread and it doesn't wait to complete to continue the code. The code is on a new thread. On this thread then I can await method.
So If I clearly understood I decided to use async await for long processes which implies an order of execution on main thread.
And I use Task.run for thread to run in parrallel and process independently.
Is it the good way and is my understanding good?
Thanks,
Your understanding of async
/ await
and Task.Run
is mostly correct.
Task.Run
allows you to easily run some code on a ThreadPool
thread and avoid blocking current thread. Creating multiple Task
s or using Parallel
class allows you take adventage of multiple CPU cores to do some work faster.
When using async
/ await
you can do some work once your task has completed. Thanks to SynchronizationContext
code after await
can be executed back on your original thread, although it is not always the case. For exaple console application has no SynchronizationContext
.
One important thing to remember is that async
/ await
is great for I/O bound work while Task.Run
is good for CPU bound work. Reason behind this is that when you await
some I/O bound operation, like sending data over network, you don't waste any thread on just waiting for such operation to complete. You can read more about thathere .
Yes, the Task.Run
method is an easy way to offload work to a background thread. The worker threads are provided by the ThreadPool
class. Learning a bit about this class is a good idea, to know what happens when the pool becomes starved, and what you can do if you anticipate this to happen (using the SetMinThreads
proactively is an option).
Using the Task.Run
is more convenient than working with Thread
instances directly. Tasks have a strongly-typed Result
, have an Exception
property, can be awaited asynchronously, can be combined with other tasks, and can be wrapped in other tasks with extra functionality (for example wrapping a task in a cancelable wrapper .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.