Home > Back-end >  Do we still need to use await in c#?
Do we still need to use await in c#?

Time:12-29

The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes

But according to this post:

//You can access the Result property of the task, 
//which will cause your thread to block until the result is available:

string code = GenerateCodeAsync().Result;

Does that mean that we don't need await anymore? Because if we use await, we have to change the function to async which complicates the logic. But accessing the result property of a task doesn't require this

Update

//code1
func1();
var r = asyncFunc().Result;
func2(); //thread block, func2 won't be called until asyncFunc completes.



//code2
func1();
await asyncFunc();
func2();  //will func2 be called immediately after "await asyncFunc()"?
          //To my understanding "await asyncFunc()" will return immediately

CodePudding user response:

100x yes - await is important. .Result will block the calling thread until the result is produced. await allows the runtime to suspend and wake up subsequent code only when needed, not blocking any thread. In practice, the await can wake up on a completely different thread.

A little tidbit of history: Task<T> and its .Result were added as part of the C# 4.0 and the Task Parallel Library, well before async & await.

CodePudding user response:

I think a common misconception with the async/await pattern is that suspending execution == blocking for the result. This however is not true. When you call await your program doesn't actually stop execution, it pushes the thread into a waiting queue which will be resurrected upon IO completion. This allows other tasks to run in the meantime. While technically you could always block for the result and have the same code output, your code will run a lot faster by using await.

CodePudding user response:

GenerateCodeAsync().Result in this case just removes asynchronous from your code.

  •  Tags:  
  • c#
  • Related