N
N
Nikita2021-04-19 04:40:22
.NET
Nikita, 2021-04-19 04:40:22

What is the role of Task.Run() and await in async methods?

Good day!
I just started to get acquainted in detail with asynchronous calls in C # and not all points are crystal clear

. For example, there is such a code, what will be the difference between 2 Thread.Sleep () calls?
The order in which messages are displayed is identical in both versions.

Example 1
607cdc96c6263292542966.png


And the second example is this, showing a variant of correct error handling using a local function
Question, why in this example is calling DoProcessing () without await? Book typo?
After all, in this case, my Completed message comes before Work done!, and why in this case await does not save Task.Run ()
Example 2
607cdee747bca221026032.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-04-19
@Mayhem924

1.Task.Run is needed to run synchronous methods in the threadpool.
2. Thread.Sleep is not recommended, because there is Task.Delay
The second example really looks like a typo.
Both examples are bad: For example, if await Task.Run is removed in the first method, then Thread.Sleep will occupy the calling thread
Read TAP.docx

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question