Hello everyone, there is an example:

class Program { static object locker = new object(); static void WriteSecond() { for (int i = 0; i < 20; i++) { lock (locker) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(new string(' ', 10) + "Secondary"); Console.ForegroundColor = ConsoleColor.Gray; Thread.Sleep(100); } } } static void Main() { Console.SetWindowSize(80, 45); ThreadStart writeSecond = new ThreadStart(WriteSecond); Thread thread = new Thread(writeSecond); thread.Start(); for (int i = 0; i < 20; i++) { lock (locker) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Primary"); Console.ForegroundColor = ConsoleColor.Gray; Thread.Sleep(100); } } // Delay. Console.ReadKey(); } } 

As you can see, two critical sections of lock are created, and they use one lock object in two different methods - one critical section in the WriteSecond method and the second in the Mian () method, but both these sections are still within the same class - the Program class. Perhaps exactly the same "separation" of the object of blocking between two critical sections, if these sections will be located in different classes? If this is possible, then I will ask you to give an example of code with an explanation to it, and if not, then why?

    1 answer 1

    Can. In your example, a locker object (it is static) can be made public and used in any other class: lock (Program.locker). The lock information is "bound" to the locker object. It makes no difference which object uses the locker to lock.

    But doing so is not very good. Usually, lock objects try to keep them as closed as possible so that it is easier to track locks when problems arise with them.