qq在线咨询杨老师 qq在线咨询王老师 qq在线咨询韩老师 qq在线咨询张老师
 
您当前位置:主页 > .NET百科 >

.NET 线程同步方法
2016-03-01 17:18

1 使用Monitor来同步
Monitor类提供两个静态方法Monitor.Enter()和Monitor.Exit()来保证代码的同步。有一点要保证的是调用了Monitor.Enter()后必须有一个相对应的Monitor.Exit()。所以,一个很好的做法是将这两个方法用一个Try/Finally块包围起来。
示例:
view plainprint?
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);
view plainprint?
           //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好一点点。
view plainprint?
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);
view plainprint?
        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时,它指定在任一时刻只允许一个线程访问这个方法。
view plainprint?
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();
       }
   }


相关信息:
·北大青鸟学士后.NET开发试题之简答题 ·ASP.NET数据处理控件 北大青鸟学士后
·北大青鸟.NET软件工程师——Web服务器验证控件 ·.NET编程——如何创建ArrayList
·.NET开发——关于输出格式化 ·ASP.Net和ASP的区别
·.NET的两大技术模块 ·ADO.NET的简介
·ADO.NET中怎么实现事务?
青鸟热门课程安卓工程师
青鸟热门课程网络营销师
青鸟热门课程网络工程师
青鸟热门课程JAVA工程师
青鸟热门课程.NET工程师
.NET行情
 
Copyright © 2002-2015 北大青鸟北京北方华腾技术培训中心 版权所有 地址:北三环中路马甸桥东北角商房大厦(国美电器)626 招生热线:010-82011433/32
京ICP备05043413号 京公网安备 11010802023056号