c# lock and deadlocks (basics)

            object A = new object();
            object B = new object();
 
            Task.Factory.StartNew(() =>
            {
                lock (A)
                {
                    Thread.Sleep(1000);
                    lock (B) Console.WriteLine("locked A, then B");
                }
            });
 
            Task.Factory.StartNew(() =>
            {
                lock (B)
                {
                    lock (A) Console.WriteLine("locked B, then A");
                }
            });

https://csharphardcoreprogramming.wordpress.com/2013/12/10/lock-and-deadlocks-basics/

When you comment Thread.Sleep line you can easily understand whats happening.

A deadlock will only occur if you have more than one lock. You need a situation where both threads hold a resource that the other needs (which means there has to be a least two resources, and the two threads have to attempt to acquire them in a different order)


Loading