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 New Object (); 2 Private ReadOnly Object 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, the test class code is as follows:

    /// <summary>    ///The parameters passed when the UI is manipulated across threads, this article simply encapsulates a message in order to display messages/// </summary>     Public classMyeventargs:eventargs { Public ReadOnly stringMessage =string.        Empty;  PublicMyEventArgs (stringmsg) {             This. Message =msg; }    }    /// <summary>    ///test class for testing the difference between 2 types of locks/// </summary>     Public classLocktest {//2 x Lock        Private Static ReadOnly ObjectLocker1 =New Object(); Private ReadOnly ObjectLocker2 =New Object(); /// <summary>        ///delegates and events that manipulate the UI across threads/// </summary>         Public Delegate voidMessageeventhandler (Objectsender, MyEventArgs e);  Public EventMessageeventhandler messageevent;  Public voidOnMessage (MyEventArgs e) {if( This. Messageevent! =NULL) Messageevent ( This, E); }        //to lock the variable, through which you can see the effect of 2 kinds of locks in different situations        Private intnum =0; //Instance Name        Private ReadOnly stringName;  PublicLocktest (stringname) {Name=name; }        //the first type of lock execution method         Public voidAddNum1 () {Lock(Locker1) {num=0;            ShowMessage (); }        }        //the second type of lock execution method         Public voidAddNum2 () {Lock(Locker2) {num=0;            ShowMessage (); }        }        //some actions within the lock, and through the event, the key message is displayed to the UI in the main thread        Private voidShowMessage () {stringmsg ="";  for(inti =0; I <Ten; i++) {num+=1; Msg=string. Format ("thread [{0}], the value of num in instance [{1}] is [{2}]", Thread.CurrentThread.Name, This.                Name, num); OnMessage (NewMyEventArgs (msg)); Thread.Sleep ( -); } msg=string. Format ("====== thread [{0}] finished executing ======", Thread.CurrentThread.Name); OnMessage (NewMyEventArgs (msg)); }    }

The test class is finished and the test begins:

First Test the difference between a single instance, a multi-threaded, 2 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 ();            }        }        private void Button2_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). ADDNUM2));                A.name = i.ToString ();                A.start ();            }        }

The output is identical:

It is concluded that there is no difference between 2 kinds of locks if there is a multi-threaded access to an instance.

The following is a case of testing multiple instances ( static locks ):

        Private voidButton3_Click (Objectsender, EventArgs e)            {listBox1.Items.Clear ();  for(inti =0; I <=2; i++) {locktest test=NewLocktest ("locktest"+i.tostring ()); Test. Messageevent+=NewLocktest.messageeventhandler (Messagecallback); Thread a=NewThread (NewThreadStart (test.                ADDNUM1)); A.name=i.tostring ();            A.start (); }        }

Get results:

It is concluded that in the presence of static locks, threads are still queued, although not an instance, but the lock is unique and the thread only locks, so the thread does not have concurrency!

Continue testing ( non-static locks ):

        Private voidButton4_Click (Objectsender, EventArgs e)            {listBox1.Items.Clear ();  for(inti =0; I <=2; i++) {locktest test=NewLocktest ("locktest"+i.tostring ()); Test. Messageevent+=NewLocktest.messageeventhandler (Messagecallback); Thread a=NewThread (NewThreadStart (test.                ADDNUM2)); A.name=i.tostring ();            A.start (); }        }

The results obtained:

Conclusion: When the non-static lock, multithreading concurrency, together in the work.

In fact, the test results can be guessed out before, but, do not test, the heart always feel no bottom, huh, ha, test finished, also completely relieved!

The code in the form, used for event callbacks, is displayed in the UI here:

Delegate voidMessageHandler (stringmsg);  Public voidMessagecallback (Objectsender, MyEventArgs e) {MessageHandler handler=NewMessageHandler (showmessage);  This. Invoke (Handler,New Object[] {e.message}); }         Public voidShowMessage (stringmsg) {             This. LISTBOX1.ITEMS.ADD (msg); }

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.