Lock is the address.
and. NET has an internal mechanism that makes the same string memory addresses the same (new string) except
The experiment 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 ("Lock 2s key=" +key); Thread.Sleep (+); Console.WriteLine ("Unlock");}}}
Run
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 S Tring (' 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 ("Lock 2s key=" +key); Thread.Sleep (+); Console.WriteLine ("Unlock");}}}
Run results from the new string
Control concurrency with lock string C #