The TryEnter () method of the Monitor class is very similar to the Enter () method, he tries to get the exclusive lock of the object, but it does not pause as an Enter () method. If the thread is successful, the TRYENTER () method returns True. TryEnter There are three overload methods, two of which have timeout parameters, indicating the time waiting to be locked.
Using system; using system.threading;
Namespace MonitorTryEnter {public class tryenter {public tryenter () {}
Public void criticalsection () {bool b = monitor.tryEnter (this, 1000); console.writeline ("thread" thread.currentthread.gethashcode () "Tryenter Value" b); for (int i = 1; i <= 3; i ) {thread.sleep (1000); console.writeline (i " thread.currentthread.gethashcode () ");} monitor.exit (this);
Public static void main () {TryEnter a = new tryenter (); thread t1 = new thread (new threadstart (a.criticalsection)); thread t2 = new thread (New ThreadStart (a.criticalSection); t1.start () T2.Start ();}}} Run results:
You can use TRYENTER () when you can compete, but you don't want the thread to sleep an unspecified time.
Lsqxw@hotmail.com