Questions about asynchronous programming

I was wondering in a rich gui application, what would happen if an awaited method was finished and ready to go back and continue the rest of the code after the await while at the same time a control on the ui was being triggered and another method needed to be ran. What would have priority in that scenario?

Also if I have a method that calls an api and that request/response takes ~250ms and I needed to call this api thousands of times more, could I use asynchronous programming to increase the performance and reduce that time it takes to make those api calls? Could I wrap the api call in a TaskCompletionSource and call it thousands of times in a for loop and do a Task.WhenAll() so that they can be performed all at once instead of synchronously (call api then wait for response then loop to make the next api call)?

11 comments · 84% upvoted · other discussions

comments

voidvector

Assuming IO operations, async simply moves "blocking" from "OS blocking your thread" to ".NET runtime blocking your execution context"

  • in synchronous code, you cede your execution to the OS scheduler. So your thread is blocked until OS has a response. Your thread is still occupying memory.
  • in asynchronous code, you cede your execution to the .NET runtime, which can allow other things happen on your thread (e.g. render UI). As a benefit, this also allows you to run concurrent code, thus giving you more scheduling control.

CPU/IO-wise, there is no performance gained. Previously you can spawn 1000 threads (assuming you have the memory) have each thread call your API.