Deep understanding of lock in C #

Source: Internet
Author: User
 lock can only use the reference type, which is strictly the instance of the object. Even if the object is the same in the sense, but if it is not referenceequals, then it will be treated as two instances, then C # lock is not the same thing. That is to say, when you think this lock takes effect, it is actually useless. Test Case: 
01 using system; 02 using system. threading; 03 04 class TTT 05 {06 private Hello test; 07 08 public TTT (Hello t) 09 {10 this. test = T; 11} 12 13 public void dotransactions () 14 {15 lock (TEST) 16 {17 for (INT I = 0; I <10; I ++) 18 {19 console. writeline (thread. currentthread. managedthreadid. tostring (); 20} 21} 22} 23} 24 25 26 class Hello 27 {28 Internal int I; 29} 30 31 32 class test 33 {34 static void main () 35 {36 thread [] threads = new thread [10]; 37 // ttt acc = new TTT (New Hello (); // When enabled, the lock takes effect, because the lock is the same instance 38 for (INT I = 0; I <10; I ++) 39 {40 TTT ACC = new TTT (New Hello ()); // when this function is enabled, the lock does not take effect because it is not 41 thread t = new thread (New threadstart (ACC. dotransactions); 42 threads [I] = T; 43} 44 for (INT I = 0; I <10; I ++) 45 {46 threads [I]. start (); 47} 48 49 console. readline (); 50} 51}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.