Synchronizing a timer to prevent overlap

后端 未结 6 2213
谎友^
谎友^ 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:36

    I'd use Monitor.TryEnter in your elapsed code:

    if (Monitor.TryEnter(lockobj))
    {
      try
      {
        // we got the lock, do your work
      }
      finally
      {
         Monitor.Exit(lockobj);
      }
    }
    else
    {
      // another elapsed has the lock
    }
    

提交回复
热议问题