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?
locks in C# are re-entrant – a single thread can acquire the same lock multiple times without blocking. Sine you only have one thread here there is no problem – locks are for synchronizing access to resources across multiple threads.
From the MSDN documentation on
lock:For more information on re-entrant-locking see this SO thread: “What is the Re-entrant lock and concept in general?”