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?