初学多线程(二)--Monitor VS lock

**1.Both Monitor class and lock provider a mechanism that synchronizes access to objects.lock is the shortcut for Monitor.Enter with try and finally.
即lock是Monitor.Enter()的简写**

private static object obj = new object();
        static void AddToMillion()
        {
            for (int i = 0; i < 1000000; i++)
            {
                lock(obj)
                {
                    total++;
                }
            }
        }       

可以写成:

private static object obj = new object();
        static void AddToMillion()
        {
            for (int i = 0; i < 1000000; i++)
            {
                Monitor.Enter(obj);
                try
                {
                    total++;
                }
                finally
                {
                    Monitor .Exit (obj );
                }
            }
        }

2.lock是简写方法,如果要实现高级进程,就要使用Montor类中的其他方法,如:TryEnter(),Wait(),Pulse()&PulseAll()等
注意Montor.Enter在C#4.0中的写法有点不一样

static object obj = new object();
        static void AddToMillion()
        {
            for (int i = 0; i < 1000000; i++)
            {
                bool lockToken = false; 
                Monitor.Enter(obj, ref lockToken);
                try
                {
                    total++;
                }
                finally
                {
                    if(lockToken)
                    Monitor .Exit (obj );
                }
            }
        }

你可能感兴趣的:(C#学习)