Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to use structured concurrency in C#

By Joydip Kanjilal, Contributor, InfoWorld |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.Structured concurrency is a strategy for handling concurrent operations in asynchronous programming. It relies on task scopes and proper resource cleanup to provide several benefits including cleaner code, simpler error handling, and prevention of resource leaks. Structured concurrency emphasizes the idea that all asynchronous tasks should be structured within a specific context, allowing developers to effectively compose and control the flow of these tasks.To better manage the execution of async operations, structured concurrency introduces the concept of task scopes. Task scopes provide a logical unit that sets boundaries for concurrent tasks. All tasks executed within a task scope are closely monitored and their lifecycle is carefully managed. If any task within the scope encounters failure or cancellation, all other tasks within that scope are automatically canceled as well. This ensures proper cleanup and prevents re­source leaks.Here are some of the key benefits of structured concurrency:In C#, we can implement structured concurrency by using the features available in the System.Threading.Tasks.Channels namespace. This namespace offers helpful constructs like Channel and ChannelReader that make implementing structured concurrency easier.Take a look at the following example code, which I will explain below.In the example code above, we establish a channel to enable communication between the main thread and concurrent tasks. The MyAsyncOperation method represents the asynchronous operation that will be executed concurrently. By using the EnterAsync method of the ChannelReader object, we enter a task scope. Here multiple tasks are scheduled and waited using a call to the the Task.WhenAll method. If any task fails or is canceled, then all other tasks within that scope also will be canceled. Lastly, the Writer instance is closed and we await the completion of the Reader.You can implement structured concurrency using the Nito.StructuredConcurrency NuGet package. Before we dive into using this package, let’s install it into the console application project we created earlier. To do this, select the project in the Solution Explorer window and right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the Nito.StructuredConcurrency package and install it.Alternatively, you can install the Nito.StructuredConcurrency package via the NuGet Package Manager console by entering the line of code below.You can create a task scope in which you can define the work to be done by your asynchronous tasks. To do this, you can use the RunGroupAsync method of the TaskGroup class as shown in the code snippet given below.In the preceeding code snippet, note how the delegate is passed to the RunGroupAsync method. This delegate represents the first work item. The subsequent work items are added to the same task group. When all the work items have completed their execution, the control exits the task group and the group is closed.In the event of an exception, the task group enters a faulted state.Task groups ignore tasks that have been cancelled, i.e., they catch and ignore any occurrences of OperationCanceledException. Additionally, task groups can own resources, which are disposed when the execution of the task group is complete.Structurеd concurrеncy offеrs a disciplinеd approach to handling concurrеnt tasks by еnsuring that tasks havе a clеar scopе and lifеtimе. It offers significant benefits in terms of code maintainability, error handling, and resource management in asynchronous programming scenarios. By following this approach, dеvеlopеrs can rеducе thе risk of common pitfalls associatеd with concurrеncy, such as dangling tasks or unhandlеd еxcеptions, lеading to morе maintainablе and rеliablе codе.Next read this:Joydip Kanjilal is a Microsoft MVP in ASP.NET, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .NET and related technologies. Copyright © 2023 IDG Communications, Inc.Copyright © 2023 IDG Communications, Inc.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

How to use structured concurrency in C#

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×