Stalli Stalli - 5 days ago 6
C# Question

Task deadlock doesn't occur

I found this example in the book. And it's written that this code leads to deadlock. But I don't get it and don't understand why it should be?
I always get


“Locked B and A”

“Locked A and B”


static void Main()
{
object lockA = new object();
object lockB = new object();
var up = Task.Run(() =>
{
lock (lockA)
{
Thread.Sleep(1000);
lock (lockB)
{
Console.WriteLine(“Locked A and B”);
}
}
});

lock (lockB)
{
lock (lockA)
{
Console.WriteLine(“Locked B and A”);
}
}

up.Wait();
Console.ReadLine();
}

Answer

The code isn't guaranteed to deadlock. There is a race condition as to whether or not it will deadlock. If the newly started task manages to grab the first lock before the main thread goes on to grab that same lock, then the code deadlocks, if (as is no doubt happening for you) the first thread manages to get both locks before the worker thread does anything, then there is no deadlock.

Comments