Home Backend Development C#.Net Tutorial Analysis of misuse points in .Net multi-threaded programming

Analysis of misuse points in .Net multi-threaded programming

Apr 10, 2017 am 10:59 AM
.net Multithreading

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); });
   }
}
Copy after login

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); });
   }
}
Copy after login

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()); });
   }
}
Copy after login

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();
   }
}
Copy after login

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);
   }
}
Copy after login

5 Unable Catching exceptions

try
{
    var task = Task.Run(() => { throw new Exception("抛异常"); });
    //如果将下面这行代码注掉,则无法抛出异常
    task.Wait();
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}
Copy after login

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);
   }
}
Copy after login

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....");
     }
    }
   });
}
Copy after login

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);
}
Copy after login

##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 =>
   {
    //业务
   });
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ function exceptions and multithreading: error handling in concurrent environments C++ function exceptions and multithreading: error handling in concurrent environments May 04, 2024 pm 04:42 PM

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.

How to implement multi-threading in PHP? How to implement multi-threading in PHP? May 06, 2024 pm 09:54 PM

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.

Usage of JUnit unit testing framework in multi-threaded environment Usage of JUnit unit testing framework in multi-threaded environment Apr 18, 2024 pm 03:12 PM

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.

How can concurrency and multithreading of Java functions improve performance? How can concurrency and multithreading of Java functions improve performance? Apr 26, 2024 pm 04:15 PM

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.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

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

How to deal with shared resources in multi-threading in C++? How to deal with shared resources in multi-threading in C++? Jun 03, 2024 am 10:28 AM

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.

Challenges and countermeasures of C++ memory management in multi-threaded environment? Challenges and countermeasures of C++ memory management in multi-threaded environment? Jun 05, 2024 pm 01:08 PM

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.

Challenges and strategies for testing multi-threaded programs in C++ Challenges and strategies for testing multi-threaded programs in C++ May 31, 2024 pm 06:34 PM

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.

See all articles