.NET 线程同步方法

1 使用Monitor来同步

Monitor类提供两个静态方法Monitor.Enter()和Monitor.Exit()来保证代码的同步。有一点要保证的是调用了Monitor.Enter()后必须有一个相对应的Monitor.Exit()。所以,一个很好的做法是将这两个方法用一个Try/Finally块包围起来。

示例:

 class Program
    {
        public const int _total = 100000;
        //声明为readonly防止在其他地方被修改
        readonly static object _sync = new object();
        static long _count = 0;
        static void Main(string[] args)
        {
            ThreadStart threadStart =new ThreadStart(DoWork);
            Thread thread = new Thread(DoWork);
            thread.Start();
           
            Thread t = Thread.CurrentThread;
            t.Name = "Main thread";
            for (int i = 0; i < _total; i++)
            {
                try
                {
                Monitor.Enter(_sync);
               //Console.Write("+");
                    _count++;
                }
                finally
                {
                    Monitor.Exit(_sync);
                }
            }
            thread.Join();
            Console.WriteLine(t.Name+"has finish");
            Console.WriteLine("Count:" + _count);
            Console.Read();
        }

        public static void DoWork()
        {
            Thread.CurrentThread.Name = " NewThread ";
            for (int i = 0; i < _total; i++)
            {
                try
                {
                    Monitor.Enter(_sync);
                    _count--;
                    //Console.Write("-");
                }
                finally
                {
                    Monitor.Exit(_sync);
                }
            }
            Console.WriteLine(Thread.CurrentThread.Name + "has finish");
            Console.WriteLine("Count:" + _count);
        }
    }


输出:

Count为0.

若把Monitor.Enter()和Monitor.Exit()注释掉的话,Count就不一定为0,特别是循环次数_total 特别大的时候。

Monitor类有一个缺点就是对性能影响很大。方法中有使用Monitor.Enter()和没有使用执行时间相差很大。

2 使用Lock关键字

如果你觉得Monitor要既要写Enter()又要调用Exit()很麻烦,那你可以使用Lock()关键字。并且使用Lock()的性能会比Monitor好一点点。

class Program
    {
        public const int _total = 100000;
        //声明为readonly防止在其他地方被修改
        readonly static object _sync = new object();
        static long _count = 0;
        static void Main(string[] args)
        {
            ThreadStart threadStart =new ThreadStart(DoWork);
            Thread thread = new Thread(DoWork);
            thread.Start();
           
            Thread t = Thread.CurrentThread;
            t.Name = "Main thread";
            for (int i = 0; i < _total; i++)
            {
                lock (_sync)
                {
                    _count++;
                }
            }
            thread.Join();
            Console.WriteLine(t.Name+"has finish");
            Console.WriteLine("Count:" + _count);
            Console.Read();
        }

        public static void DoWork()
        {
            Thread.CurrentThread.Name = " NewThread ";
            for (int i = 0; i < _total; i++)
                lock (_sync)
                {
                    _count--;
                }
            }
            Console.WriteLine(Thread.CurrentThread.Name + "has finish");
            Console.WriteLine("Count:" + _count);
        }
    }


3 MethodImplAttribute类

MethodImplAttribute会告诉CLR方法是如何实现的,其属性设置为MethodImplOptions.Synchronized时,它指定在任一时刻只允许一个线程访问这个方法。

 class MethodImpi
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void DoSomeWorkSync()
        {
            Thread.CurrentThread.Name="Sync"+DateTime.Now.Ticks;
            Console.WriteLine("DoSomeWorkSync() --Lock  by Thread" + Thread.CurrentThread.GetHashCode());
            Thread.Sleep(5 * 1000);
            Console.WriteLine("DoSomeWorkSync() --Released by Thread" + Thread.CurrentThread.GetHashCode());
        }

        public static void DoSomeWorkNoSync()
        {
            Thread.CurrentThread.Name = "Sync" + DateTime.Now.Ticks;
            Console.WriteLine("DoSomeWorkNoSync() --Lock  by Thread" + Thread.CurrentThread.GetHashCode());
            Thread.Sleep(5 * 1000);
            Console.WriteLine("DoSomeWorkNoSync() --Released by Thread" + Thread.CurrentThread.GetHashCode());
        }
        static void Main(string[] args)
        {
            Thread th1 = new Thread(DoSomeWorkSync);
            Thread th2 = new Thread(DoSomeWorkSync);
            th1.Start();
            th2.Start();

            Thread th3 = new Thread(DoSomeWorkNoSync);
            Thread th4 = new Thread(DoSomeWorkNoSync);
            th3.Start();
            th4.Start();
        }
    }


结果:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值