为什么我不能获得独家锁?

时间:2009-04-13 20:04:38

标签: c# multithreading locking

以下程序打印:

Entered 3
Entered 4
Wait for Exited messages
Exited 3
Exited 4

意味着它无法获取资源的独占锁。为什么呢?

public class Worker
    {
        public void DoIt(object resource)
        {
            Monitor.Enter(resource);
            Console.WriteLine("Entered " + Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(3000);
            Monitor.Exit(resource);
            Console.WriteLine("Exited " + Thread.CurrentThread.ManagedThreadId);
        }
    }

    class Program
    {
        struct Resource
        {
            public int A;
            public int B;
        }

        static void Main(string[] args)
        {
            Resource resource;
            resource.A = 0;
            resource.B = 1;

            var a = new Worker();
            var b = new Worker();

            var t1 = new Thread(() => a.DoIt(resource));
            var t2 = new Thread(() => b.DoIt(resource));

            t1.Start();
            t2.Start();

            Console.WriteLine("Wait for Exited messages");
            Console.ReadLine();
        }
    }

1 个答案:

答案 0 :(得分:10)

您的Resource是一个结构。它传递给DoIt时会被装箱,因此每次调用DoIt都会锁定一个不同的对象。将Resource更改为班级。