


Analysis of misuse points in .Net multi-threaded programming
This article mainly introduces the analysis of misuse points in .Net multi-threaded programming. It has certain reference value, let’s take a look at it with the editor
1 Shared variable problem
Wrong writing:
All tasks may share the same variable, so the output results may be the same.
public static void Error() { for(int i=0;i<10;i++) { Task.Run(() => { Console.WriteLine("{0}", i); }); } }
Correct writing:
Assign variable i to local variable temp, so that Each task uses a different i value.
public static void Right() { for (int i = 0; i < 10; i++) { int temp = i; Task.Run(() => { Console.WriteLine("{0}", temp); }); } }
2 Do not clean up the resources required for pending tasks
Wrong way of writing:
Asynchronously output text content, so when the StreamReader is not used, the variable sr has left its scope and the Dispose method is called.
public static void Error() { using (StreamReader sr = new StreamReader(@"D:\说明.txt", Encoding.Default)) { Task.Run(() => { Console.WriteLine("输出:{0}",sr.ReadLine()); }); } }
Correct writing:
public static void Right() { using (StreamReader sr = new StreamReader(@"D:\说明.txt", Encoding.Default)) { var task = Task.Run(() => { Console.WriteLine("输出:{0}", sr.ReadLine()); }); task.Wait(); } }
3 Avoid locking this, typeof(type), string
The correct approach: define a private read-only field of object type and lock it.
4 Regarding WaitHandle.WaitAll, the number of waitHandles must be less than or equal to 64
public static void Error() { ManualResetEvent[] manualEvents = new ManualResetEvent[65]; try { for (int i = 0; i < 65; i++) { var temp = i; Task.Run(() => { manualEvents[temp] = new ManualResetEvent(false); Console.WriteLine("{0}", temp); manualEvents[temp].Set(); }); } WaitHandle.WaitAll(manualEvents); } catch (Exception ae) { Console.WriteLine(ae.Message); } }
5 Unable Catching exceptions
try { var task = Task.Run(() => { throw new Exception("抛异常"); }); //如果将下面这行代码注掉,则无法抛出异常 task.Wait(); } catch(Exception ex) { Console.WriteLine(ex.Message); }
6 Should Task resources be released?
It is recommended to call Dispose, but not The call isn't a serious mistake either.
Note that resources are not allowed to be released when the Task is in certain states, otherwise an error will be reported.
public static void CatchException() { try { Console.WriteLine("开始"); var task = Task.Run(() => { //throw new Exception("抛异常"); }); //注掉下面这行代码,观察异常结果 //task.Wait(); task.Dispose(); Console.WriteLine("结束"); } catch(Exception ex) { Console.WriteLine(ex.Message); } }
7 Deadlock Demonstration
Assume that both tsak1 and task2 are A deadlock occurs when the first lock is successfully acquired before the second lock is acquired (for tsak1, the second lock requested is LockedObj2, and for task2, it is LockedObj1).
private static readonly Object LockedObj1 = new object(); private static readonly Object LockedObj2 = new object(); public static void LockShow() { var task1 = Task.Run(() => { lock (LockedObj1) { Console.WriteLine("get LockedObj1"); lock (LockedObj2) { Console.WriteLine("get LockedObj2...."); } } }); var task2 = Task.Run(() => { lock (LockedObj2) { Console.WriteLine("get LockedObj2"); lock (LockedObj1) { Console.WriteLine("get LockedObj1...."); } } }); }
Multiple runs can produce the following two results: the first picture is a situation where deadlock does not occur, and the second picture is when a deadlock occurs. situation.
8 Do not call the Thread.Abort method.
Task does not provide the Abort method. If you use the new TPL (after .NET 4.0), you will not think of this problem. CancellationToken is generally used to control the cancellation of tasks.
9 Make sure shared variables are safe
Run repeatedly, you can observe different results, as shown in the figure below.
public static void Func() { string s = "ASDFGH"; Parallel.Invoke( () => { s = s.Replace("A", "1"); s = s.Replace("S", "1s"); }, () => { s = s.Replace("A", "2"); s = s.Replace("S", "2s"); }, () => { s = s.Replace("A", "3"); }); Console.WriteLine(s); }
##10 Processor Oversubscription and Underapplication
public static void Func() { ParallelOptions po = new ParallelOptions(); //超额申请,处理器只有4个逻辑内核,结果设置并行度为10且是个逻辑内核均在工作,等待的任务数量大于0. po.MaxDegreeOfParallelism = 10; //申请不足,处理器有4个逻辑内核,却指定并行度为3,还有一个空闲的内核没有被占用(也有可能被其他线程占用,这里假设在指定并行度为3的情况下,另一个内核空闲) po.MaxDegreeOfParallelism = 3; List<int> list = new List<int>(); Parallel.ForEach(list, po, m => { //业务 }); }
The above is the detailed content of Analysis of misuse points in .Net multi-threaded programming. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

PHP multithreading refers to running multiple tasks simultaneously in one process, which is achieved by creating independently running threads. You can use the Pthreads extension in PHP to simulate multi-threading behavior. After installation, you can use the Thread class to create and start threads. For example, when processing a large amount of data, the data can be divided into multiple blocks and a corresponding number of threads can be created for simultaneous processing to improve efficiency.

There are two common approaches when using JUnit in a multi-threaded environment: single-threaded testing and multi-threaded testing. Single-threaded tests run on the main thread to avoid concurrency issues, while multi-threaded tests run on worker threads and require a synchronized testing approach to ensure shared resources are not disturbed. Common use cases include testing multi-thread-safe methods, such as using ConcurrentHashMap to store key-value pairs, and concurrent threads to operate on the key-value pairs and verify their correctness, reflecting the application of JUnit in a multi-threaded environment.

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Mutexes are used in C++ to handle multi-threaded shared resources: create mutexes through std::mutex. Use mtx.lock() to obtain a mutex and provide exclusive access to shared resources. Use mtx.unlock() to release the mutex.

In a multi-threaded environment, C++ memory management faces the following challenges: data races, deadlocks, and memory leaks. Countermeasures include: 1. Use synchronization mechanisms, such as mutexes and atomic variables; 2. Use lock-free data structures; 3. Use smart pointers; 4. (Optional) implement garbage collection.

Multi-threaded program testing faces challenges such as non-repeatability, concurrency errors, deadlocks, and lack of visibility. Strategies include: Unit testing: Write unit tests for each thread to verify thread behavior. Multi-threaded simulation: Use a simulation framework to test your program with control over thread scheduling. Data race detection: Use tools to find potential data races, such as valgrind. Debugging: Use a debugger (such as gdb) to examine the runtime program status and find the source of the data race.
