How to implement concurrent programming in C#

1. Multi-threading: It is a concurrent programming technology that allows an application to execute multiple threads at the same time. Each thread has its own instruction set and stack, and can run in parallel on different CPU cores, or run alternately on one CPU core through time slice rotation. The main advantage of multi-threading is that it can take advantage of the performance of multi-core processors. The disadvantage is that synchronization and communication between threads may be more complicated and may also lead to problems such as data competition.

2. Asynchronous: It is a programming paradigm that allows operations to be performed simultaneously without having to wait for one to complete before executing another. Asynchronous operations can be implemented through callback functions, Promise, or the language's async/await syntax. The main advantage of asynchronous programming is that it can improve the responsiveness of the program and avoid blocking the main thread. It is especially suitable for processing I/O-intensive tasks, such as network requests, file reading and writing, etc. The disadvantage is that it may lead to complex code logic and may also cause problems such as callback hell.

Async is not multithreading . Asynchronous and multithreading are concepts at different levels, although they can work together to achieve concurrent programming in some cases.

Asynchronous is a programming model that does not occupy the CPU all the time when a task is executed, but hangs when encountering an I/O operation or waiting for other events, and then resumes task execution after the asynchronous operation is completed. This model can improve the responsiveness and efficiency of the program, especially when handling I/O-intensive tasks such as network requests or file reading and writing.

Multithreading is another concurrent programming model that uses multiple threads to perform tasks simultaneously to improve program performance. Multithreading is suitable for handling CPU-intensive tasks as it leverages the performance of multi-core processors.

In some cases, asynchronous and multi-threading can be used together, such as leveraging multi-threading in asynchronous operations to improve efficiency, or using asynchronous operations in multi-threaded programs to avoid blocking the main thread. However, they are not directly equivalent or substitutes for each other.

Processing and concurrent programming methods provided by .NET:

  1. Task Parallel Library (TPL) : TPL is a library in the .NET Framework for writing parallel and concurrent code. It provides a set of APIs and tools that simplify the complexities of parallel programming. TPL supports data parallelism and task parallelism, and can implement parallel loops and parallel execution delegation through methods such as Parallel.For, Parallel.ForEach, and so on.Parallel.Invoke
  2. Parallel LINQ (PLINQ) : PLINQ is a parallel version of LINQ that allows parallel query operations to be performed on data collections. With PLINQ, LINQ queries can be converted into parallel operations, thereby improving performance.
  3. Background Worker : Background Worker is a component in .NET used to perform time-consuming operations on a background thread. It can perform long-running tasks without blocking the UI thread and is suitable for applications such as Windows Forms and WPF.
  4. Threads and Thread Pools : .NET also provides support for underlying threads and thread pools. You can use System.Threading.Threadclasses to create and manage threads, or to System.Threading.ThreadPoolleverage thread pool resources to perform parallel operations.
  5. Async/Await : Asynchronous programming is another way to deal with concurrency, which can avoid blocking the main thread and improve the responsiveness of the application. In .NET, async/awaitasynchronous programming can be achieved through asynchronous methods and keywords. Asynchronous methods can execute long-running tasks without creating new threads, but achieve non-blocking execution through mechanisms such as asynchronous IO and Task.
  6. Dataflow : Dataflow is a library introduced in .NET 4.5 for building message-based parallel and distributed applications. It provides a set of block types that can be used to create message producers and consumers, and implements parallel execution and message delivery through the Dataflow Graph.
  7. ** lock-free and wait-free data structures **: In .NET, you can also use lock-free and wait-free data structures to achieve high-performance concurrent programming. These data structures allow multiple threads to access shared resources simultaneously without using locks or other synchronization mechanisms.

Implementation:

1. Use List<Task>

List<Task> tasks = new List<Task>();
foreach (string model in models.Split(','))
{
    string read_file_name = $"{model}-BOX-{dateTime.ToString("yyyyMMdd")}.csv";
    string write_file_name = $"{model}-BOX数据生成-{dateTime.ToString("yyyyMMdd")}.csv";
    tasks.Add(Task.Run(() => { ReadWriteFile(read_file_name,write_file_name); }));
}
Task.WaitAll(tasks.ToArray());//等待List里的Task任务全部执行完成,防止阻塞

Guess you like

Origin blog.csdn.net/weixin_50478033/article/details/133129963