Home  >  Article  >  Backend Development  >  Analysis of misuse points in .Net multi-threaded programming

Analysis of misuse points in .Net multi-threaded programming

怪我咯
怪我咯Original
2017-04-10 10:59:311896browse

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!

Statement:
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