Monitor is no different from lock but the monitor class provides more control over the synchronization of various threads trying to access the same lock of code. It can be done by acquiring a significant lock so that only one thread can enter in a given piece of code at one time. Monitor provides a mechanism that synchronizes access to objects. The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement and then releasing the lock. If another thread tries to enter a locked code, it will wait, block, until the object is released. The method TestLock is invoked ten times, but the tick count shows the protected method region is executed sequentially, about 100 milliseconds apart. The Main method creates ten new threads and then calls Start on each one. When the method TestLock is called many times on new threads, each invocation of the method accesses the threading primitives implemented by the lock. Here we see a static method " TestLock" that uses the lock statement on an object. ThreadStart start = new ThreadStart(TestLock) Console.WriteLine(Environment.TickCount) Ģ1. static readonly object _object = new object() ġ3.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |