C#方法同步 [MethodImpl(MethodImplOptions.Synchronized)]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;

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

        //[MethodImpl(MethodImplOptions.Synchronized)]
        public void ExecuteAnother()
        {
            Console.WriteLine("Thread Name:{1},Excute Another at {0}", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(2000);
        }
    }

    delegate int del(int i);

    class Program
    {
        static void Main(string[] args)
        {
            SyncHelper helper = new SyncHelper();

            TimerCallback func = (obj) => {
                helper.Execute();
            };

            TimerCallback funcAnother = (obj) =>
            {
                helper.ExecuteAnother();
            };

            Timer timer = new Timer(func, null, 0, 1000);

            Timer timerAnother = new Timer(funcAnother, null, 0, 1000);

            /*
            Expression<del> myET = x => x * x;
            Console.WriteLine(myET.Compile().Invoke(2));
            */



            /*
            Timer timer = new Timer(
              delegate
              {
                  helper.Execute();
              }, null, 0, 1000);
            */

            Console.Read();

        }
    }
}

  

posted @ 2014-01-04 10:40  庚武  Views(1657)  Comments(0Edit  收藏  举报