About mutual exclusion of C #

Source: Internet
Author: User

Please correct me for your personal understanding and experience in the following error.

C # provides three mutually exclusive monitor classes, lock, and mutex classes, with the following differences and how to use them:

First, lock class

Called "Critical Zone", the package version of Monitor, used for multi-threading, is useless for single-threaded, that is, supports multiple calls to lock within the same thread to lock the same target.

Usage

            Lock (this) {                 //Execute code            }

Effect to invoke the same function within multiple threads, the function internally uses a locking method that allows the thread to "queue" until the lock ends, and then other functions can queue up to the next execution code.

Wait for an infinite wait until the occupation is released, otherwise the thread is blocked.

Note: It is not recommended to lock the public object (with This,typeof (Type), "string"), and do not use this in the same way as the example above, which is strongly deprecated, because if you lock your own, there may be an external lock on the object, Causes the same object to be locked inside multiple functions, which can affect efficiency. The following recommendations are used

        Private Object New Object ();          Public void Test ()        {            lock  (obj)            {                // Execute code             }        }

Second, monitor class

Consistent with lock effect, using different methods

        Private Objectobj =New Object();  Public voidTest () {if(System.Threading.Monitor.TryEnter (obj, +))//wait 1 seconds in line            {                //Execute CodeSystem.Threading.Monitor.Exit (obj);//Exit            }            Else            {                //waiting in line, it's not going to wait.            }        }

It can be seen that the difference is increased time, that is, if the queue is impatient, can not wait, and leave the team, for this, System.Threading.Monitor also provides a number of functions to use

Enter attempts to get an object, while the second optional parameter returns whether the success was obtained

TryEnter attempts to get an object and sets the wait time for the attempt on the second optional parameter

Wait releases the obtained object and tries to get the object again after the second optional parameter time (i.e., after you queue up to yourself, arrange your data to stop for a while, give it to someone else, and then proceed)

Exit releases the obtained object, similar to wait, but does not block the current thread and does not attempt to get the object again

Pulse (), PULSEALL () sends a signal to one or more waiting threads, indicating that they are about to release the object, please be prepared, usually called before exit or wait, to improve performance.

Third, the Mutex class

The name is a mutex (mutex, mutex), which can be used for multi-threading and functions like monitor, but its main purpose is not for multi-threading, but for processes.

The feature is still that a thread with executive power can have multiple times, but it must also be released multiple times.

How to use

        Private StaticSystem.Threading.Mutex Mutex =NULL;//set to static members to hold mutexes throughout the program life cycle        /// <summary>        ///The main entry point for the application. /// </summary>[STAThread]Static voidMain () {BOOLfirstinstance; Mutex=NewSystem.Threading.Mutex (true,"name", outfirstinstance); if(!firstinstance) {MessageBox.Show ("exist"); return; }        }

The main is 2 functions ReleaseMutex and WaitOne, the former is released, the latter is waiting to release the signal.

The first argument to the constructor of the above code is whether to get it immediately, the second parameter is the name of the mutex, the note is global, it can not be filled out as anonymous, but if it is filled it can no longer create a mutex with the same name (including different software, it is recommended to use the program name).

About mutual exclusion of C #

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.