25

我正在编写一个 Windows 服务,它每隔一段时间运行一个可变长度的活动(数据库扫描和更新)。我需要经常运行此任务,但要处理的代码不能安全地同时运行多次。

我怎样才能最简单地设置一个计时器以每 30 秒运行一次任务,同时又不重叠执行?(我假设System.Threading.Timer是这项工作的正确计时器,但可能是错误的)。

4

6 回答 6

36

您可以使用计时器来执行此操作,但您需要对数据库扫描和更新进行某种形式的锁定。一个简单lock的同步可能足以防止发生多次运行。

话虽这么说,最好在操作完成后启动一个计时器,只使用一次,然后停止它。下次操作后重新启动它。这将使您在事件之间有 30 秒(或 N 秒),没有重叠的机会,也没有锁定。

例子 :

System.Threading.Timer timer = null;

timer = new System.Threading.Timer((g) =>
  {
      Console.WriteLine(1); //do whatever

      timer.Change(5000, Timeout.Infinite);
  }, null, 0, Timeout.Infinite);

立即工作......完成......等待 5 秒......立即工作......完成......等待 5 秒......

于 2009-03-26T01:36:50.227 回答
29

我会在您经过的代码中使用 Monitor.TryEnter :

if (Monitor.TryEnter(lockobj))
{
  try
  {
    // we got the lock, do your work
  }
  finally
  {
     Monitor.Exit(lockobj);
  }
}
else
{
  // another elapsed has the lock
}
于 2009-03-26T01:43:59.460 回答
19

我更喜欢System.Threading.Timer这样的事情,因为我不必通过事件处理机制:

Timer UpdateTimer = new Timer(UpdateCallback, null, 30000, 30000);

object updateLock = new object();
void UpdateCallback(object state)
{
    if (Monitor.TryEnter(updateLock))
    {
        try
        {
            // do stuff here
        }
        finally
        {
            Monitor.Exit(updateLock);
        }
    }
    else
    {
        // previous timer tick took too long.
        // so do nothing this time through.
    }
}

您可以通过将计时器设置为一次性并在每次更新后重新启动它来消除对锁定的需求:

// Initialize timer as a one-shot
Timer UpdateTimer = new Timer(UpdateCallback, null, 30000, Timeout.Infinite);

void UpdateCallback(object state)
{
    // do stuff here
    // re-enable the timer
    UpdateTimer.Change(30000, Timeout.Infinite);
}
于 2009-03-26T03:48:37.537 回答
2

而不是锁定(这可能会导致所有定时扫描等待并最终叠加)。您可以在线程中启动扫描/更新,然后检查线程是否仍然存在。

Thread updateDBThread = new Thread(MyUpdateMethod);

...

private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    if(!updateDBThread.IsAlive)
        updateDBThread.Start();
}
于 2009-03-26T03:24:24.600 回答
1

您可以按如下方式使用 AutoResetEvent:

// Somewhere else in the code
using System;
using System.Threading;

// In the class or whever appropriate
static AutoResetEvent autoEvent = new AutoResetEvent(false);

void MyWorkerThread()
{
   while(1)
   {
     // Wait for work method to signal.
        if(autoEvent.WaitOne(30000, false))
        {
            // Signalled time to quit
            return;
        }
        else
        {
            // grab a lock
            // do the work
            // Whatever...
        }
   }
}

一个稍微“更智能”的解决方案在伪代码中如下所示:

using System;
using System.Diagnostics;
using System.Threading;

// In the class or whever appropriate
static AutoResetEvent autoEvent = new AutoResetEvent(false);

void MyWorkerThread()
{
  Stopwatch stopWatch = new Stopwatch();
  TimeSpan Second30 = new TimeSpan(0,0,30);
  TimeSpan SecondsZero = new TimeSpan(0);
  TimeSpan waitTime = Second30 - SecondsZero;
  TimeSpan interval;

  while(1)
  {
    // Wait for work method to signal.
    if(autoEvent.WaitOne(waitTime, false))
    {
        // Signalled time to quit
        return;
    }
    else
    {
        stopWatch.Start();
        // grab a lock
        // do the work
        // Whatever...
        stopwatch.stop();
        interval = stopwatch.Elapsed;
        if (interval < Seconds30)
        {
           waitTime = Seconds30 - interval;
        }
        else
        {
           waitTime = SecondsZero;
        }
     }
   }
 }

这些中的任何一个都有一个优点,即您可以关闭线程,只需发出事件信号即可。


编辑

我应该补充一点,此代码假设您只有其中一个 MyWorkerThreads() 正在运行,否则它们将同时运行。

于 2009-03-26T04:23:49.137 回答
1

当我想要单次执行时,我使用了互斥锁:

    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
                {
                      //<your code here>
                }
                finally
                {
                    onlyOne.ReleaseMutex();
                }
            }
        }

    }

抱歉,我来晚了...您需要在 GetMutexName() 方法调用中提供互斥锁名称。

于 2015-09-02T20:19:51.207 回答