Controlling concurrency through lock strings C#

lock locks the address

And .net has an internal mechanism to make the same string memory address the same (new string) except

The experimental code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> keyList = new List<string> { "key1","key2", "key1", "key1", "key1", "key1", };
 
            keyList.ForEach(u =>
            {
                ThreadPool.QueueUserWorkItem(s =>
                {
                    test.lockTestByString(u);
                });
 
            });
 
            Console.Read();
        }
    }
    public class test {
 
        public static void lockTestByString(string key)
        {
            lock (key)
            {
                Console.WriteLine("上锁2s key="+key);
                Thread.Sleep(2000);
                Console.WriteLine( " Unlock " );
 
            }
        }
 
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> keyList = new List<string> {new string('k',1), new string('k', 1), new string('k', 1), new string('k', 1) };
 
            keyList.ForEach(u =>
            {
                ThreadPool.QueueUserWorkItem(s =>
                {
                    test.lockTestByString(u);
                });
 
            });
 
            Console.Read();
        }
    }
    public class test {
 
        public static void lockTestByString(string key)
        {
            lock (key)
            {
                Console.WriteLine("上锁2s key="+key);
                Thread.Sleep(2000);
                Console.WriteLine( " Unlock " );
 
            }
        }
 
    }
}

The result of running through the new string

 

 Reprinted from: https://www.cnblogs.com/ProDoctor/p/7619847.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324736016&siteId=291194637