Asynchronous Programming with C#

This post contains affiliate links and Generous Dev gets commissions for purchases made through these links in this post. See the Disclaimer page for more information

In the world of software development, often you don’t need to wait for one method to finish before moving on. In this scenario, it is recommended to use asynchronous programming with C#. The solution below gives a simple example on how to use this to make your program run more efficiently.

The Asynchronous Solution

This is an example that simulates waking up two people, Bob and Jane. The NonAsyncWakeUp method can’t proceed until each person wakes up. Alternatively, the AsyncWakeUp method can tell the next person to wake up immediately after telling the first.

    class Program
    {
        static void Main(string[] args)
        {
            StartWakeUp();
            StartWakeUpAsync();
            Console.ReadKey();
        }
        static async void StartWakeUp()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("Starting the synchronous part of the program...");
            await WakeUpBobAsync();
            await WakeUpJaneAsync();
            sw.Stop();
            Console.WriteLine("Total SYNCHRONOUS time: " + sw.Elapsed.TotalSeconds + " seconds");
        }
        static async void StartWakeUpAsync()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("Starting the Asynchronous part of the program...");
            List<Task> tasks = new List<Task>();
            tasks.Add(Task.Run(() => WakeUpBobAsync()));
            tasks.Add(Task.Run(() => WakeUpJaneAsync()));
            await Task.WhenAll(tasks);
            sw.Stop();
            Console.WriteLine("Total ASYNC time: " + sw.Elapsed.TotalSeconds + " seconds");
        }
        static async Task WakeUpBobAsync()
        {
            Console.WriteLine("Hey Bob wake up!");
            System.Threading.Thread.Sleep(10000);
            Console.WriteLine("This is Bob, I'm now awake");
        }
        static async Task WakeUpJaneAsync()
        {
            Console.WriteLine("Hey Jane wake up!");
            System.Threading.Thread.Sleep(5000);
            Console.WriteLine("This is Jane, I'm now awake");
        }
    }

Measuring Asynchronous vs Synchronous

Here is the output of running the code above:

Starting the synchronous part of the program...
Hey Bob wake up!
This is Bob, I'm now awake
Hey Jane wake up!
This is Jane, I'm now awake
Total SYNCHRONOUS time: 15.0167587 seconds
Starting the Asynchronous part of the program...
Hey Jane wake up!
Hey Bob wake up!
This is Jane, I'm now awake
This is Bob, I'm now awake
Total ASYNC time: 10.0160015 seconds

As you can see, the asynchronous code took 5 seconds faster in total. Also, instead of waiting 10 seconds to wake up Jane, we could wake her up immediately after telling Bob. This allowed Jane to wake up about 5 seconds before Bob wakes up instead of 5 seconds after.

Why Use Asynchronous Programming?

The answer here is simple. Why don’t we stare at our ovens for 15 minutes while frozen pizza is cooking? Because we could be doing other things at this time. We could be making a salad. We could be setting the table. If we had to wait for each step of cooking to finish before proceeding, making dinner will take so much longer. Running synchronous code causes the same problems. We want our programs to be efficient and finish processing sooner rather than later. For this reason, you should identify all areas of your code that can be converted to asynchronous methods.

When To Not Use Asynchronous Programming

Often your program can’t proceed until certain methods complete. You may need to run business logic on a list of database records. In this case, you need to wait for the database response before starting that business logic.

The rule of thumb is that you shouldn’t use asynchronous programming on methods that generally take 50ms or less to complete. There may be more overhead in complexity and even CPU time for it to be worth it.

The Await Operator in Asynchronous Programming

The await operator in asynchronous programming identifies which async methods you want to wait to complete. This is useful with UI applications because the awaited code won’t block the thread that evaluates the async method. This is especially useful for applications with a UI.

The Async Naming Convention

The general rule for asynchronous programming is add the Async suffix to the end of your methods. This will signal to the consumers of your apis or methods which are awaitable.

In Conclusion

Asynchronous programming with C# is an extremely powerful and often overlooked part of developing software. For long running methods, it can shave off a significant amount of time. I hope this simple example has shown why to consider using it for your applications.

Recommended Products On This Topic

  

Programmer Humor Apparel

 

Subscribe to be notified of new posts

You can also subscribe the Generous Dev Youtube Channel for free videos.

Leave a Reply

Your email address will not be published.