SoFunction
Updated on 2025-03-07

Detailed explanation of several methods of high concurrency in C# programming

Concurrency is actually a very general concept, which literally means "doing multiple things at the same time", but the methods are different. In the world of .NET, there are roughly the following ways to deal with high concurrency:

1. Asynchronous programming

Asynchronous programming is to use future mode (also known as promise) or callback mechanism to implement (Non-blocking on waiting). If you use callbacks or events to implement (easy to callback hell), not only will it be unintuitive to write such code, but it will quickly make the code mess.

However, the async/await keyword introduced in .NET 4.5 and above (can be used by adding packages in .NET 4.0) makes writing asynchronous code easy and elegant. By using the async/await keyword, you can write asynchronous code like writing synchronous code. All callbacks and event processing are left to the compiler and runtime for you to handle, which is simple and easy to use.

There are two benefits to using asynchronous programming: it does not block the main thread (such as UI threads) and improves the throughput of server applications. Therefore, Microsoft recommends that it uses asynchronous requests by default.

For example: I use asynchronously to push WeChat template messages.

/// <summary>
/// Test the asynchronous template message interface using asynchronous Action/// </summary>
/// <param name="checkcode"></param>
/// <returns></returns>
public async Task<string> TemplateMessageAsync(string openId, string first, string keyword1, string keyword2, string keyword3, string keyword4, string remark, string url)
{
 if (openId == null)
 {
 return ReturnString(7771, "OPENID cannot be empty");
 }
 else
 {
 var testData = new //TestTemplateData()
 {
  first = new TemplateDataItem(first),
  keyword1 = new TemplateDataItem(keyword1),
  keyword2 = new TemplateDataItem(keyword2),
  keyword3 = new TemplateDataItem(keyword3),
  keyword4 = new TemplateDataItem(keyword4),
  remark = new TemplateDataItem(remark)
 };

 var result = await (_wechat.APPID, openId, "m6td4jp_heMA5rhopbUaHApOlp2DD5x18BMXWKj3M5U", url, testData);
 return ReturnString(0, "success");
 }
}


2. Parallel programming

The emergence of parallel programming actually emerged with the multi-core CPUs, with the goal of making full use of the computing power of multi-core CPUs. Parallel programming will increase the utilization rate of the CPU and is more suitable for some client applications, which may have a negative impact on server applications (because the server itself has the characteristics of parallel processing, such as IIS will process multiple requests in parallel). The scenario where I use parallel programming the most is when I analyzed the uncertainty of the environment data before, I used parallel method to calculate Monte Carlo simulation (computing thousands of times after computing). Of course, I later used Taylor series expansion to calculate the uncertainty. Without so much calculation, there is no need to be parallel. Of course, when comparing the results of multiple schemes, concurrent calculations are still used.

In .NET, parallel support mainly relies on the task parallel library and parallel LINQ introduced by .NET 4.0. Through these libraries, data processing can be achieved (the processing method is the same, the input data is different, such as the application scenarios I mentioned above) or task processing (the processing method is different, and data isolation). By using parallel processing libraries, you don't have to care about the creation and management of Tasks (not to mention the underlying threads), you just need to focus on the processing tasks themselves.

The specific usage is still a referenceOfficial Documentation

3. Responsive programming

Responsive programming has recently become a Buzzword. In fact, Microsoft began providing .NET with Reactive Extensions 6 years ago. It’s a bit difficult to understand responsive programming at the beginning, but once you understand it, you will be fond of its power. Simply put, responsive programming treats event streams as data streams, but data streams are pulled from IEnumable, and event streams are pushed to you from IObservable. Why can responsive programming achieve concurrency? This is because Rx is thread-agnostic. Every time an event is triggered, subsequent processing will arbitrarily take out any thread from the thread pool to process. And you can set window periods and current limits for events. For example, you can use Rx to delay the search text box (rather than using a timer to delay it very early).

The best way to learn more about Rx is to browse this website, and of course there is alsoOfficial Documentation

4. Data flow programming

DataFlow programming may be even more unfamiliar with it, but there are still some common scenarios that can be solved using data flow. Data flow is actually a set of data processing extensions derived from the Task Parallel Library (TPL) (also combined with asynchronous features). TPL is also the basic library for handling task parallelism and data parallelism in parallel programming.

The meaning of the article is to make a series of processing of data. First, a set of mesh is defined for such processing. Forks, connections, and loops can be defined in the mesh. Data flowing into such a processing grid can be processed in parallel. You can think that a grid is an upgraded version of the pipeline, but in fact it is often used as a pipeline. The use scenario can be "analyzing word frequency in a text file" or "handling producer/consumer issues".

Of course, reference materials areOfficial Documentation

5. Actor model

Scala has Akka, but Microsoft Research has also launched Orleans to support the implementation of the Actor model, and of course it is also available. The goal of Orleans design is to facilitate programmers to develop cloud services that require large-scale expansion, which can be used to implement DDD+EventSourcing/CQRS systems.

Official websiteCheck.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.