Prevent multiple instance of a service - best approach?

后端 未结 6 1690
醉话见心
醉话见心 2020-12-05 05:31

So what do you think is the best way to prevent multiple threads of a C# Windows service running simultaneously (the service is using a timer with the OnE

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 05:54

    Instead of lock you can use Monitor.TryEnter() to return if a callback is already being executed by another timer thread:

    class Program
    {
        static void Main(string[] args)
        {
            Timer t = new Timer(TimerCallback, null,0,2000);
            Console.ReadKey();
        }
    
        static object timerLock = new object();
    
        static void TimerCallback(object state)
        {
            int tid = Thread.CurrentThread.ManagedThreadId;
            bool lockTaken = false;
            try
            {
                lockTaken = Monitor.TryEnter(timerLock);
                if (lockTaken)
                {
                    Console.WriteLine("[{0:D02}]: Task started", tid);
                    Thread.Sleep(3000); // Do the work 
                    Console.WriteLine("[{0:D02}]: Task finished", tid);
                }
                else
                {
                    Console.WriteLine("[{0:D02}]: Task is already running", tid);
                }
            }
            finally
            {
                if (lockTaken) Monitor.Exit(timerLock);
            }
        }
    }
    

提交回复
热议问题