Introduction

This lesson gives a gentle introduction to asynchronous programming in C#.

Introduction

In this part of the course, we'll explain the motivation for and the basics of asynchronous programming in C#. Treat it like a gist or summary on the subject and not an in-depth tutorial. After completing this section, you should have a fair grasp of how asynchronous programming works in C# minus the minutiae.

Concurrency can be defined as dealing with multiple things at once. You can concurrently run several processes or threads on a machine with a single CPU but you'll not be parallel when doing so. Concurrency allows us to create an illusion of parallel execution even though the single CPU machine runs one thread or process at a time.

Parallelism is when we execute multiple things at once. True parallelism can only be achieved with multiple CPUs.

So far we've delved into the threading API of C#. But there's another paradigm of achieving concurrency using asynchronous programming. What is it? Let's work through an analogy:

Consider a restaurant with a single waiter. Suddenly, three customers, Kohli, Amir and John show up. The three of them take a varying amount of time to decide what to eat once they receive the menu from the waiter. Let's assume Kohli takes 5 minutes, Amir 10 minutes and John 1 minute to decide. If the single waiter starts with Amir first and takes his order in 10 minutes, next he serves Kohli and spends 5 minutes on noting down his order and finally spends 1 minute to know what John wants to eat then in total, he spends 10 + 5 + 1 = 16 minutes to take down their orders. However, notice in this sequence of events, John ends up waiting 15 minutes before the waiter gets to him, Kohli waits 10 minutes and Amir waits 0 minutes.

Now ...