I recently changed from the NodeJS team to work in the .Net team (in the same company). Coming back to C# after a long time, there are a lot of new stuffs. Actually, I used to hate .Net (simply because I hate using Windows :LOL:). But thing has changed. .Net Core can now run on non-Windows systems without any differences. It is becoming easier to develop .Net applications on Mac/Linux (using Jetbrains Rider like me or Visual Studio Community for Mac, which is a bad idea).
One interesting thing that I found in C# after a long time working in JS is the Async/Await operation, which simplifies asynchronous programming significantly. I heard that JS borrows the Async/Await idea from C#, so I decided to take a deeper look at the Async/Await operation in C# and compare it to the one in JS to see if there are any other things that C# is more successful at. There may be things that I was wrong about because I’m relatively new to C#.
Below is the comparison table between using Async/Await pattern in C# and JS. I also mentioned JS Generator because it can be applied pretty much in the same way as the one using Promise. Actually, it used to be an innovative way to solve asynchronous problems in JS before the birth of Async/Await. Many teams and products are still using it as the code base was developed many years ago. Today, Async/Await is the preferred way for handling asynchronous tasks in JS, leaving Generator back to its original purpose.
|C#||JS (yield)||JS (Async/Await)|
|Traditional Method||TPL - Callbacks||Callbacks||Callbacks|
|Invoke||Immediately||When calling yield||Immediately|
|The operation is executed immediately after calling the async method||Calling a generator function returns a generator object only||The operation is executed immediately after calling the async method|
|Postpone Execution||Wrap in a Lambda expression||No need||Wrap in a function|
|Use Cases||I/O & CPU-bound tasks||I/O||I/O|
|JS is single-threaded, Generator doesn’t help with CPU-bound tasks||JS is single-threaded, Promise doesn’t help with CPU-bound tasks|
|Support||Native, C# 5+||Native, but not all environments||Native (newer JS versions)|
|Requires 3rd-party libraries for async programming||Use polyfill libraries in old JS environment|