Asynchronous programming using C#
Synchronous execution refers to the line by line execution of code. It is easy to write and maintain such code, assuming best practices were followed during development and there is no spaghetti mess. The issue happens when a long running process executes. Synchronous technique will block any other activity until this process runs. For example, in a desktop application if the user triggers a long running process that has been created synchronously, the user will not be able to perform anything else (even say moving the window etc.) while the process is running.
This is where asynchronous programming shines. It is a means to perform different operations concurrently i.e. in parallel. Asynchronous programming is the general concept where lots of different operations are running at the same time, concurrency is the code we write and parallelism is dependent on the hardware where the code has been deployed.
Benefits of asynchronous programming includes better user experience, utilizing the available multiple cores for computation and the use of cloud computing where modern applications have resources present at different locations across the globe and performance becomes a key parameter.
Why is hard to work with asynchronous code?
Applications developer employ the use of threads for asynchronous programming. Threads of an operating system share some of the resources of the process they are living in. When multiple threads are reading and writing to the database concurrently, it becomes really hard to manage different threads. Thread safety measures makes the code indeterministic and hard to understand and further machine dependent.
A working example to understand asynchronous execution
Imagine there are four tasks to perform. After completing the first task and starting the second one, you find a few things need to be verified with a vendor. You give them a call and they say they will get back to you in an hour. You are blocked! Would you sit idle and do nothing until they call back with answer? That would be highly inefficient. You pick up the next task and finish it. And when the vendor calls back with the answers, you return to the blocked task and continue working.
This is in essence what asynchronous programming is.
Mechanisms of asynchronous programming