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
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceconsoleapp5{classProgram {Static voidMain (string[] args) {List<string> keylist =Newlist<string> {"Key1","Key2","Key1","Key1","Key1","Key1", }; Keylist.foreach (U={ThreadPool.QueueUserWorkItem (s={test.locktestbystring (U); }); }); Console.read (); } } Public classTest { Public Static voidLocktestbystring (stringkey) { Lock(Key) {Console.WriteLine ("lock 2s key="+key); Thread.Sleep ( -); Console.WriteLine ("Unlock"); } } }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceconsoleapp5{classProgram {Static voidMain (string[] args) {List<string> keylist =Newlist<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 classTest { Public Static voidLocktestbystring (stringkey) { Lock(Key) {Console.WriteLine ("lock 2s key="+key); Thread.Sleep ( -); Console.WriteLine ("Unlock"); } } }}
Run results from the new string
Transferred from: https://www.cnblogs.com/ProDoctor/p/7619847.html
Control concurrency with lock string C #