Take you easy to understand C# Lock keywords

I believe that most .NET players, like me, often use the Timer object, and there are many people who use DispatcherTimer in WPF. DispatcherTimer runs on the UI thread. Most of our programs will be filled with a lot of Timer, it can be understood that it is a thread, it inherits from System.Windows.Threading.

  There may be some static variables or singleton objects in the program to allow different pages to interact, but this provides a basis for fighting between each thread. Because the resource is separate, it is like a person who steps on two boats, and it will definitely overturn. For example, a List collection, you operate on it in one thread, in another thread at the moment of synchronization, if you do not handle it carefully, it will cause "the collection has been modified; the enumeration operation may not be performed". Of course, we are not talking about collection-related issues, but about resource allocation. Of course, resource grabbing occurs in time-consuming threads, such as the picture below.

 

 

  This time-consuming operation, and in the synchronization thread, the thread is not encapsulated, it is easy to cause resource grabbing problems. If the Object is a collection, I change it in the middle, and other threads will read it dirty in the next second. If there is an error, we can pass the Lock keyword.

  First of all, the description of Lock in the Microsoft documentation is that the lock keyword can be used to ensure that the code block finishes running without being interrupted by other threads. This is achieved by acquiring a mutex lock for a given object while the code block is running.

  But what we need to pay attention to is that Lock is essentially Monitor.Enter, Monitor.Enter will box the value type, and each Lock is the boxed object. Lock is actually syntactic sugar similar to a compiler, so the compiler directly restricts the value type that cannot be locked. Why, think about it carefully, every time you box is a different object, how can I judge? object.ReferenceEquals is false every time...the other thing is that you don’t want to lock the string. Simply put, after the Lock string, as long as you have the same string match as the content in your Lock, that character The string will also be locked, which is equivalent to a deadlock.

  The difference between Lock and Monitor is not very big, see the following code for details.

private static object obj = new object();

        public void LockSomething()

        {

            lock (obj)

            {

                dosomething();

            }

        }

        public void MonitorSomeThing()

        {

                Monitor.Enter(obj);

                dosomething();

                Monitor.Exit(obj);

        }

        public void dosomething()

        { 

            //Do specific things

        }

 Lock and Monitor are implemented by .NET with a special structure. The Monitor object is fully managed, fully portable, and may be more effective in terms of operating system resource requirements. The synchronization speed is faster, but it cannot be synchronized across processes. The main function is to lock the critical section so that the code in the critical section can only be executed by the thread that acquired the lock. Monitor.Wait and Monitor.Pulse are used for thread synchronization, similar to signal operations. Personally, I feel that it is more complicated to use and may cause deadlock.

  The lock is to encapsulate the Monitor.Enter and Monitor.Exit methods. In fact, it is not difficult to understand. As long as you determine when the Lock is used and how to use it, you can summarize it. It is often used to prevent multi-threaded operations from causing uncertain abnormalities in the value of public variables to ensure the safety of operations.

Guess you like

Origin blog.csdn.net/weixin_43144260/article/details/106660557