代码改变世界

深入理解c#中的lock

2010-08-26 22:32  田志良  阅读(1073)  评论(0编辑  收藏  举报

lock只能使用引用类型,严格来说是需要对象的实例。即使对象在意义上是相同的,但是如果不是ReferenceEquals的话,那么将作为两个实例来对待,那么C# lock 的就不是同一个东西。也就是说,当你以为这个 lock 生效的话,它其实在做无用工。

测试用例:

using System;
using System.Threading;

class TTT
{
    private hello test;

    public TTT(hello t)
    {
        this.test = t;
    }

    public void DoTransactions()
    {
        lock (test)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
            }
        }
    }
}


class hello
{
    internal int i;
}


class Test
{
    static void Main()
    {
        Thread[] threads = new Thread[10];
        //TTT acc = new TTT(new hello());  //启用此处,lock会生效,因为lock的是同一个实例
        for (int i = 0; i < 10; i++)
        {
            TTT acc = new TTT(new hello());  //启用此处,lock不会生效,因为lock的不是同一个实例
            Thread t = new Thread(new ThreadStart(acc.DoTransactions));
            threads[i] = t;
        }
        for (int i = 0; i < 10; i++)
        {
            threads[i].Start();
        }

        Console.ReadLine();
    }
}