Synchronizing a timer to prevent overlap

后端 未结 6 2203
谎友^
谎友^ 2020-12-08 21:02

I\'m writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn

6条回答
  •  自闭症患者
    2020-12-08 21:53

    I've used a mutex when I've wanted single execution:

        private void OnMsgTimer(object sender, ElapsedEventArgs args)
        {
            // mutex creates a single instance in this application
            bool wasMutexCreatedNew = false;
            using(Mutex onlyOne = new Mutex(true, GetMutexName(), out wasMutexCreatedNew))
            {
                if (wasMutexCreatedNew)
                {
                    try
                    {
                          //
                    }
                    finally
                    {
                        onlyOne.ReleaseMutex();
                    }
                }
            }
    
        }
    

    Sorry I'm so late...You will need to provide the mutex name as part of the GetMutexName() method call.

提交回复
热议问题