class Class1
{
private static object consoleGate = new Object();
private static void Trace(string msg)
{
lock (consoleGate)
{
Console.WriteLine("[{0,3}/{1}]-{2}:{3}", Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.IsThreadPoolThread ? "pool" : "fore",
DateTime.Now.ToString("HH:mm:ss.ffff"), msg);
}
}
private static void ProcessWorkItems()
{
lock (consoleGate)
{
for (int i = 0; i < 5; i++)
{
Trace("Processing " + i);
Thread.Sleep(250);
}
}
Console.WriteLine("Terminado.");
}
static void Main()
{
ProcessWorkItems(); Console.ReadLine();
}
}
output:
Processing 0
Processing 1
Processing 2
Processing 3
Processing 4
Terminated
Why is this code works? ProcessWorkItems static method locks ConsoleGate object and Trace did the same. I thought the object could only be locked once. ¿Some explanations?