Research on Lock (lock) in C # and actions across the threading UI

Source: Internet
Author: User

This article focuses on the lock (lock) used for multithreading synchronization in C # as a research object. Because you want to display the results more intuitively, so, in doing the demo, the multi-threaded through the event UI code also written out, left as a memo and share it.     in fact, multi-threaded synchronization, the use of synchronous locking method used several times, today inadvertently see MSDN, recommended by:  1 private static readonly Object locker1 = new Object ( ); 2 Private ReadOnly Object locker2 = new Object (); Note: The original text did not add ReadOnly, I added in the later.   Not only did I think about their differences.   Then I wrote a piece of code to test, test the class code as follows:  copy code    //<summary>   ///cross-threading the UI when passing parameters, this article in order to display the message, So a simple package of a    //</summary>    public class myeventargs:eventargs    {        Public readonly string Message = String. empty;        public MyEventArgs (String msg)         {        & nbsp   this. Message = msg;       }   }   //<summary>   //test class for testing 2 types of lock zones Do not    //</summary>    public class locktest    {       //2 lock &nbs P     &nbsp private static readonly Object Locker1 = new Object ();        Private ReadOnly Object Locker2 = new OB Ject ();        /<summary>       ///cross-threading UI delegation and events     &NB Sp  //</summary>        public delegate void Messageeventhandler (object sender, Myeventarg S e);        public event Messageeventhandler messageevent;        public void OnM Essage (MyEventArgs e)         {            if (this. Messageevent! = null) messageevent (this, e);       }        //variables to be locked through which you can see 2 kinds of lock effects in different situations         private int num = 0;       //Instance name         Private readonly string name;        public locktest (string Name)         {  & nbsp         Name = name;       }       //The first method of lock execution         public void Addn UM1 ()         {            Lock (Locker1)         &NBS P   {                num = 0;              and nbsp ShowMessage ();           }       }       //second lock execution Method         public void AddNum2 ()         {            Lock (Locker2)             {                num = 0;                 showmessage ();           }  &N Bsp    }       //Lock some operations, and through the event, the key message displayed to the main thread in the UI         private void SHOWM Essage () &NBsp       {            String msg = "";            for (int i = 0; i < i++)             {                num + = 1;                msg = string. Format ("thread [{0}], the value of num in instance [{1}] is [{2}]", Thread.CurrentThread.Name, this. Name, num);                OnMessage (New MyEventArgs (msg));      &N Bsp         Thread.Sleep (+);           }        &NBSP ;   msg = string. Format ("====== thread [{0}] finished executing ======", Thread.CurrentThread.Name);            OnMessage (new MyEventArgs (msg));       }    The copy code test class is finished, start testing:  first Test a single instance, multi-threading, the difference between 2 kinds of locks: private void Button1_Click (object sender, EventArgs e) {    locktest test = new Locktest ("Locktest 1 ");    test. Messageevent + = new Locktest.messageeventhandler (messagecallback);    listBox1.Items.Clear ();    for (int i = 0; I <= 2; i++)     {        Thread A = new Thread (new ThreadStart (test). ADDNUM1);        a.name = i.tostring ();        A.start ();   }}&NBSP;PR ivate void Button2_Click (object sender, EventArgs e) {    locktest test = new Locktest ("Locktest 1");  &nbsp ; Test. Messageevent + = new Locktest.messageeventhandler (messagecallback);    listBox1.Items.Clear ();    for (int i = 0; I <= 2; i++)     {        Thread A = new Thread (new ThreadStart (test). ADDNUM2));        a.name = i.tostring ();        A.start ();   }} output result one mode As:    concludes: If you have access to multiple threads in one instance, there are no differences between the 2 types of locks.   Below is the case of testing multiple instances (static lock):  copy code         private void Button3_Click (object sender, EventArgs e)         {            ListBox1. Items.clear ();            for (int i = 0; I <= 2; i++)             {                locktest test = new Locktest ("Locktest" + i.tostring ()); nbsp               test. Messageevent + = new Locktest.messageeventhandler (messagecallback);                Thread A = new Thread (new ThreadStart (test). ADDNUM1);                a.name = i.tostring ();                A.start ();           }       } Copy the code to get the result: &NBSP;&NB SP; It concludes that in the presence of a static lock, the thread is still queued, though not an instance, but the lock is unique and the thread is only locked, so the thread does not have concurrency!   Continue testing (non-static lock):  copy code         private void Button4_Click (object sender, EventArgs E)         {            listBox1.Items.Clear ();            for (int i = 0; I <= 2; i++)             {        &NBSP ;       Locktest test = new Locktest ("Locktest" + i.tostring ());            &N Bsp   Test. Messageevent + = new Locktest.messageeventhandler (messagecallback);                Thread A = new Thread (new ThreadStart (test). ADDNUM2);                a.name = i.tostring ();                A.start ();           }       } Copy code results: &NBSP;&N BSP; Come to the conclusion: when the non-static lock, multithreading concurrency, work together.     actually, the test results can be guessed out before, but, do not test, the heart always feel no bottom, hehe, the test is over, also completely relieved! The     form, used for event callbacks, is displayed in the UI code here:  Copy Code delegate void MessageHandler (String msg);       public void Messagecallback (object sender, MyEventArgs e)         {      & nbsp     MessageHandler handler = new MessageHandler (showmessage);            this. Invoke (Handler, new object[] {e.message});       }         public void Sho Wmessage (String msg)         {            THIS.LISTBOX1.ITEMS.ADD (msg), & nbsp      }

Research on Lock (lock) in C # and actions across the threading UI

Related Article

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.