Free mag vol1 | Page 779

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING } } // Print out numbers. Console.Write("Your numbers: "); for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write("{0}, ", i); } Console.WriteLine(); you have effectively designed a method that will allow the current thread to complete its task. Once a thread enters into a lock scope, the lock token (in this case, a reference to the current object) is inaccessible by other threads until the lock is released after the lock scope has exited. Thus, if thread A has obtained the lock token, other threads are unable to enter any scope that uses the same lock token until thread A relinquishes the lock token.  Note If you are attempting to lock down code in a static method, simply declare a private static object member variable to serve as the lock token. If you now run the application, you can see that each thread has ample opportunity to finish its business: *****Synchronizing Threads ***** -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, -> Worker thread Your numbers: 0, 724 #0 1, #1 1, #3 1, #2 1, #4 1, #5 1, #7 1, #6 1, #8 1, #9 1, is 2, is 2, is 2, is 2, is 2, is 2, is 2, is 2, is 2, is 2, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9, executing PrintNumbers() 3, 4, 5, 6, 7, 8, 9,