SoFunction
Updated on 2025-03-07

Overview of the introduction tutorial for C# concurrent programming

Write in front

Concurrent programming has always existed, but it has been difficult to achieve in the past long time. With the development of the Internet and the release of demographic dividends, more friendly support for concurrent programming has become the standard configuration of mainstream programming languages. For software developers, it would be a bit embarrassed to have never played concurrent programming. This series of articles will focus on C# language and introduce concurrent programming in detail.

What is concurrent programming? It is actually very simple. Concurrent programming is to do multiple things at the same time on a processor. The goal of concurrent programming is to make full use of each core of the processor to achieve the highest processing performance. For example, the server responds to the second request while responding to the first request.

Several misunderstandings about concurrent programming

Misunderstanding 1: Concurrent programming is multi-threading

In fact, multi-line is just a form of concurrent programming. There are many more practical and convenient concurrent programming technologies in C#, including asynchronous programming, parallel programming, TPL data flow, responsive programming, etc.

Misunderstanding 2: Only large server programs need to consider concurrency

Large programs on the server side must respond to data requests from a large number of clients, and of course they must fully consider concurrency. However, desktop programs and mobile applications such as mobile phones and tablets also need to consider concurrent programming because they are directly aimed at the end users, and users are now increasingly demanding on user experience. The program must be able to respond to user operations at any time, especially during background processing (reading and writing data, communicating with the server, etc.), which is one of the purposes of concurrent programming.

Misunderstanding 3: Concurrent programming is very complicated and requires mastering many underlying technologies

C# and .NET provide many libraries, and concurrent programming has become much easier. In particular, .NET 4.5 has introduced new async and await keywords, which minimizes concurrent programming code.

The direction of concurrent programming

Multi-threaded

A thread is an independent operating unit, the smallest unit that can perform operational scheduling in the operating system. It is contained in the process and is the actual operating unit in the process. Each thread has its own independent stack, but shares memory with other threads within the process. Today's .NET programs maintain a thread pool with a certain number of worker threads. These threads are waiting to execute the assigned tasks. The thread pool can also monitor the number of threads at any time for developers to handle flexibly according to business conditions.

Parallel programming

Parallel programming is mainly used to decompose computationally intensive task fragments and assign them to multiple threads. The premise is that tasks in the program can be divided into multiple independent task blocks, and the keywords are independent of each other. If the dependency is too large, it is not suitable for parallel programming.

Parallel programming utilizes the idle resources of the CPU, fully improving the utilization rate of the CPU and improving the system throughput. In most cases, the server itself already has parallel processing capabilities. When performing parallel processing through programming, it is necessary to be cautious, because improper use will lead to risks such as memory overflow. At the same time, the server itself's parallel processing capabilities will be significantly reduced due to the occupation of server resources. In severe cases, the system cannot be used. Therefore, when programming, try not to deal with tasks that are too long or too short.

Parallel processing is divided into data parallelism and task parallelism. In fact, they both use dynamically adjusted segmentation algorithms and allocate them to worker threads after task segmentation. Parallel programming can be implemented in the following two ways, one is the more beautiful PLINQ, which is the recommended processing method for parallel programming, and they come with an algorithm that automatically assigns tasks, which can be adjusted at runtime;

When writing parallel tasks, you need to pay attention to the risks brought by closures. Because closures capture references rather than values, these variables can be shared inadvertently. A better deal is that when using variables outside the closure, local variables can be defined within the closure to avoid the variable sharing problems caused by closures.

It should be noted that the thread pool will increase the number of threads as needed. The thread pool uses a work steal queue to achieve as efficient as possible.

Asynchronous programming

The most commonly used asynchronous programming model at present is TAB programming (task-based programming mode). Asynchronous programming improves responsiveness and achieves scalability. What is more intuitive is that when dealing with Winform, everyone has encountered the situation where the interface is stuck. Asynchronous programming can continue to input from the corresponding user during the program running without causing the interface to be stuck, and improves the TPS (Transactions Per Second) and QPS (Queries Per Second) of the server-side application.

After .NET 4.5, async and await keywords were introduced for asynchronous programming. The async keywords were added to the method declaration and were mainly used to match the await keywords in the method. The introduction of these two keywords makes C# more elegant in asynchronous programming. As shown below

 public async Task DelayAsync()
 {
 await (1000);
 }

The execution process of asynchronous programming is generally that when the system runs to await, it will be paused and the current online text can be captured. SynchronizationContext. If the online text is empty, the current TaskScheduler will be used, and the method will continue to be executed in this online text. After the code is executed, it will try to resume running in the original context.

Notice:When running winform and requests, the UI context or context will be used, and in other cases, the thread pool context will be used.

The waiting methods of asynchronous methods include await and Task<T>.Result. But to avoid using Task<T>.Result, because they will cause deadlocks in UI threads or thread environments. This place needs to explain the deadlock problem

 public async Task DelayAsync()
 {
  await (1000);//Capture the current context and try to continue running in the captured context }
 
 void Test()
 {
  Task task= DelayAsync();
  ();//Synchronous program block, waiting for the asynchronous method to complete ======== Blocking thread }

The UI or context can only run one thread at a time. The Wait method has blocked a thread, so the context cannot be captured while await. You can use the ConfigureAwait method to set the parameter continueOnCaptureContext to false. This can bring a revelation, which is to use ConfigureAwait(false) on thread pool threads to recover in the user interface or interface code.

An important principle in asynchronous programming is that when you use asynchronous programming, it is best to use it all the time, which is also to prevent deadlocks.

Optimized use:

Avoid continuing online articles. Too many continuation tasks will lead to performance problems

If an async method needs to use the context and the other does not need to use it, you can consider splitting it into two async methods, so that the code organization will be more intuitive.

Write to the end

The above is just an introduction to C# concurrent programming, and the knowledge points of C# concurrent programming will be introduced in detail later. Of course, there are other contents in C# concurrent programming, such as responsive programming and TPL data streaming. I usually use it less, so I won't introduce it here. Interested students can check it out.

OK, the above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.