文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>深入理解c#中的lock

深入理解c#中的lock

时间:2010-08-26  来源:田志良

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();
    }
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载