How to use structured concurrency in C#

By Akash
on 03-11-2023 11:24 AM

Structured concurrency offers a more organized and more intuitive way of managing the lifetimes of asynchronous tasks. Here’s how to take advantage of it in C#.

Modern programming languages such as C# facilitate the efficient use of resources by allowing multiple operations to be executed concurrently. Here concurrently often means asynchronously, when multiple processes must share the same CPU core. However, managing concurrent execution paths (using threads or tasks) can quickly become challenging due to the overhead of juggling asynchronous tasks.“Structured concurrency” is a programming paradigm that was introduced to address this. Structured concurrency promotes a more disciplined and organized way to manage concurrency. In this article, we will delve into structured concurrency and see how it can be implemented in C#.
First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .

NET Core console application project.We’ll use this .NET 7 console application project to work with structured concurrency in the subsequent sections of this article.
Asynchronous programming allows applications to perform resource-intensive operations concurrently, without having to block on the main or the executing thread of the application. Traditional approachеs to async programming, likе using callback functions or thе Task Parallеl Library (TPL), oftеn fall short whеn it comеs to managing concurrеncy and controlling thе lifеtimе of asynchronous opеrations. Structurеd concurrеncy offеrs a morе structurеd and intuitive way of managing asynchronous programming.