How I learned Asnyc c#
Asynchronous programming and design patterns have become quite common in every programming language and C# is no exception here. I was learning c# recently and so sharing my learning experience for this specific territory.
Before going into it, a natural question would be why I am learning it? Let's try to answer that first:
Pros and Cons of Async Programming:
- Async programming is generally used when we have I/O bound tasks so thread won't get blocked upon I/O bound tasks and can utilize CPU well.
- It is also good for CPU bound code.... by executing CPU bound tasks in background.
If you go through any courses, they will start with Async and Await so let's discuss about them first:
Async Await
The core of Async programming is Task and Task<T> object models.
For I/O bound processes await method can be used for the method which are implementing async and returning Task or Task<T> object. For CPU bound processes we can use await method over the background processes (usually Task.Run()).
Await method is the place where the magic happens it passes control on to caller method (one which is calling await) hence, as a consequence our web pages or services don't have to wait for the services to be finished.
Let me share some code snippets which helped me in understanding the general usage:
1) I/O bound instance: This method is triggered by UI, and it downloads a file (I/O process). After reaching await method controlled is yielded to UI and it can perform other actions i.e. it doesn't have to wait. petty cool!
2) CPU bound instance: Let's say we are playing a game in which a player fires a gun and does some damage. Damage calculation at the instant can be a costly operation and can UI to stop. So, to improve UI smoothness we can make damage calculation as a background function using task.run() and await.
I have worked in JS world to and from my current understanding this looks quite similar to the promise world i.e., whenever a await keyword is encountered the execution is yielded and is resumed once the background task (task written under async method) is complete.
Pro Tip: After doing all these things always check the performance of the code sometimes there can be other issues which can be induced due to OS (like context switching) which may impact the performance.
This was about waiting for one task what if we want to do it for multiple tasks?
Personally, I would have gone with a for loop calling method with await call but in documentation there seems to be a different way. There are methods called Tasks.WhenAll(), Tasks.WhenAny() which performs asynchronous non-blocking calls for multiple jobs. Let's see a snippet for the same:
References:
Comments
Post a Comment