This question has already been answered:
- Need async / await or not? 5 replies
I read a lot of literature, but I still canβt understand how await and async . Well, at least kill. Everywhere examples with httpclient, but for me they are not clear. I'm trying to figure it out myself. Here is what I understood:
As soon as our code encounters await, control returns. After completion of the expected operation, the method is restored. More precisely continues to perform from the place where he stopped when faced with await.
Ok, I wrote a couple of lines of code (maybe I just did something wrong)
async Task myMethod() { int sum = 0; await SomeCycleAsync(); Console.WriteLine("Π²ΡΠΏΠΎΠ»Π½ΠΈΠ»ΡΡ ΡΠΈΠΊΠ»2"); } async Task SomeCycleAsync() { var myTask = await ResultOfCycle(); Console.WriteLine("Π²ΡΠΏΠΎΠ»Π½ΠΈΠ»ΡΡ ΡΠΈΠΊΠ»1"); } async Task < int > ResultOfCycle() { int sum = 0; for (int i = 0; i < 1000000000; i++) { sum += i; } return sum; } private void Form1_Load(object sender, EventArgs e) { myMethod(); } In the
myMethodmethod, the wordawaitoccurs and, as far as I understand, the control should go back toform_load, right?During the execution of the
SomeCycleAsyncmethod,awaitis encountered, i.e. logically, management should go toConsole.WriteLine("Π²ΡΠΏΠΎΠ»Π½ΠΈΠ»ΡΡ ΡΠΈΠΊΠ»2");But the result of this work is:
run cycle1
run cycle2
Please explain to me why? I don't understand at all
awaitis an operator that says "wait until the result is received". The control does not go somewhere - at that moment the thread stops and waits untilSomeCycleAsyncreturns the result. The whole point is to send the task for processing, go about your business, and callawaitonly when you need the result of an asynchronous function. So you can quite flexibly work with braking operations without blocking and full multithreading. - etki