代码改变世界

[MethodImpl(MethodImplOptions.Synchronized)]

2015-07-24 16:36  xchit  阅读(404)  评论(0编辑  收藏  举报

  在NopCommerce项目的Nop.Core类库中有一个EngineContext类中有一个Initialize方法用到了[MethodImpl(MethodImplOptions.Synchronized)]

 /// <summary>
        /// Initializes a static instance of the Nop factory.
        /// </summary>
        /// <param name="forceRecreate">Creates a new factory instance even though the factory has been previously initialized.</param>
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static IEngine Initialize(bool forceRecreate)
        {
            if (Singleton<IEngine>.Instance == null || forceRecreate)
            {
                var config = ConfigurationManager.GetSection("NopConfig") as NopConfig;
                Singleton<IEngine>.Instance = CreateEngineInstance(config);
                Singleton<IEngine>.Instance.Initialize(config);
            }
            return Singleton<IEngine>.Instance;
        }

 我的理解它和Lock差不多,是解决多线程同步问题的;

 该方法一次只能由一个线程执行。 静态方法锁定类型,而实例方法锁定实例。 在任何实例函数中只能执行一个线程,并且在类的任何静态函数中只能执行一个线程。

  • 如果[MethodImplAttribute(MethodImplOptions.Synchronized)]被应用到instance method,相当于对当前实例加锁。
  • 如果[MethodImplAttribute(MethodImplOptions.Synchronized)]被应用到static method,相当于当前类型加锁。

实例方法锁定实例

class Program
    {
    //在入口Main方法中,创建SyncHelper对象,通过一个System.Threading.Timer对象实现每隔1s调用该对象的Execute方法:
static void Main(string[] args) { SyncHelper sync = new SyncHelper(); Timer timer = new Timer(delegate { sync.Execute(); }, null, 0, 1000); Console.ReadKey(); } } class SyncHelper { public void Execute() { Console.WriteLine("Excute at {0}", DateTime.Now); Thread.Sleep(5000); } }

 class Program
    {
        static void Main(string[] args)
        {
            SyncHelper sync = new SyncHelper();
            Timer timer = new Timer(delegate
            {
                sync.Execute();
            }, null, 0, 1000);

            Console.ReadKey();
        }
    }

    class SyncHelper
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Execute()
        {
            Console.WriteLine("Excute at {0}", DateTime.Now);
            Thread.Sleep(5000);
        }
    }

静态方法锁定类型

 class Program
    {
        static void Main(string[] args)
        {
            SyncHelper sync = new SyncHelper();
            Timer timer = new Timer(delegate
            {
                SyncHelper.Execute();
            }, null, 0, 1000);

            Console.ReadKey();
        }
    }

    class SyncHelper
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void Execute()
        {
            Console.WriteLine("Excute at {0}", DateTime.Now);
            Thread.Sleep(5000);
        }
    }

例子:http://www.cnblogs.com/artech/archive/2008/10/17/1313209.html