Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Monitor Class to achieve Thread synchronization in C #

Shulou Source: shulou.com Published: 2022-05-31 20:47:05 09月25日 Update

This article mainly explains "C # how to use Monitor class to achieve thread synchronization", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "C # how to use Monitor class to achieve thread synchronization" bar!

I. brief introduction

The Lock keyword is an alternative use of Monitor, and lock is translated into Monitor in IL code.

Lock (obj) {/ / Code snippet} / / is equivalent to Monitor.Enter (obj); / / Code snippet Monitor.Exit (obj)

Common properties and methods of Monitor:

Enter (Object) acquires an exclusive lock on the specified object.

Exit (Object) releases the exclusive lock on the specified object.

Pulse notifies threads in the waiting queue of changes in the state of the locked object.

PulseAll notifies all waiting threads of a change in the state of the object.

TryEnter (Object) attempts to acquire an exclusive lock for the specified object.

TryEnter (Object, Boolean) attempts to acquire an exclusive lock on the specified object and automatically sets a value indicating whether the lock has been obtained.

Wait (Object) releases the lock on the object and blocks the current thread until it reacquires the lock.

There are two commonly used methods

The Monitor.Enter (object) method is to acquire the lock

The Monitor.Exit (object) method releases the lock

These are the two most commonly used methods of Monitor. In order to avoid that the lock cannot be released because of an exception after acquiring the lock, you need to release the lock (Monitor.Exit ()) in the finally {} structure after try {} catch () {}.

Code 1.Enter (Object) case

The use of Enter (Object) is simple. Look at the code.

Class Program {static void Main (string [] args) {Thread threadA = new Thread (ThreadMethod); threadA.Name = "A"; Thread threadB = new Thread (ThreadMethod); threadB.Name = "B"; threadA.Start (); threadB.Start (); Thread.CurrentThread.Name = "C"; ThreadMethod () Console.ReadKey ();} static object obj = new object (); public static void ThreadMethod () {Monitor.Enter (obj); / / Monitor.Enter (obj) stable object try {for (int I = 1; I)

Tags: Methods objects threads code synchronization caching commonly used learning two key content that is time case status result face deadlock attempt success Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Microsoft OPPO Reno MySQL Shulou Information