轮询 Windows 服务的计时器

4

我编写了一个Timer类,以便在轮询另一个系统的Windows服务中使用它。我这样做是因为我有两个问题,而System.Timers.Timer没有解决。

  1. Elapsed EventHanler在后台运行,因此如果主线程结束,其执行将中止。我希望System.Timers.Timer.Stop函数能阻塞主线程,直到Elapsed EventHanler的执行结束。
  2. System.Timers.Timer不能处理事件重入。我希望Interval在两个Elapsed EventHanler之间,以便定时器不会在前一次调用(+interval)尚未完成时调用Elapsed EventHanler。

在编写这个类时,我发现自己需要处理一些涉及线程的问题,由于我在这方面经验不太丰富,所以想知道以下Timer类是否是线程安全的?

public class Timer
{
    System.Timers.Timer timer = new System.Timers.Timer() { AutoReset = false };
    ManualResetEvent busy = new ManualResetEvent(true);

    public double Interval
    {
        get { return timer.Interval; }
        set { timer.Interval = value; }
    }

    public Timer()
    {
        timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
    }

    void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        try
        {
            busy.Reset();
            OnElapsed(e);
            timer.Start();
        }
        finally
        {
            busy.Set();
        }
    }

    public event EventHandler Elapsed;

    protected void OnElapsed(EventArgs e)
    {
        if (Elapsed != null)
        {
            Elapsed(this, e);
        }
    }

    public virtual void Start()
    {
        busy.WaitOne();
        timer.Start();
    }

    public virtual void Stop()
    {
        busy.WaitOne();
        timer.Stop();
    }
} 
4个回答

6
首先,根据我的经验,您可以使用System.Threading.Timer代替此计时器,因为那是一个性能更好的计时器(这只是个人经验建议)。
其次,在这种情况下,您应该提供一个标志,一旦早期计时器完成任务就会设置该标志(该标志-静态字段,由所有线程访问)。
在这种情况下,请确保即使发生任何错误,您也要重置标志,以便其他计时器不会无限等待,如果计时器任务由于任务内部发生的错误而无法为其他计时器设置标志(类似于添加最终块以确保处理错误并始终重置标志)。
一旦重置了此标志,则下一个线程会对其进行操作,因此此检查将确保所有线程按顺序逐个启动任务。
以下是我为这种情况编写的示例代码(方法代码已被删除,这将向您提供设计详细信息)。
namespace SMSPicker
{
 public partial class SMSPicker : ServiceBase{
    SendSMS smsClass;
    AutoResetEvent autoEvent;
    TimerCallback timerCallBack;
    Timer timerThread;
    public SMSPicker()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        // TODO: Add code here to start your service.
        smsClass = new SendSMS();
        autoEvent = new AutoResetEvent(false);
        long timePeriod = string.IsNullOrEmpty(ConfigurationSettings.AppSettings["timerDuration"]) ? 10000 : Convert.ToInt64(ConfigurationSettings.AppSettings["timerDuration"]);
        timerCallBack = new TimerCallback(sendSMS);
        timerThread = new Timer(timerCallBack, autoEvent, 0, timePeriod);
    }


    private void sendSMS(object stateInfo)
    {
        AutoResetEvent autoResetEvent = (AutoResetEvent)stateInfo;
        smsClass.startSendingMessage();
        autoResetEvent.Set();
     }

    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down necessary to stop your service.
        smsClass.stopSendingMessage();
        timerThread.Dispose();            

    }
}
}







namespace SMSPicker
{
class SendSMS
{
    //This variable has been done in order to ensure that other thread does not work till this thread ends
    bool taskDone = true;
    public SendSMS()
    {

    }

    //this method will start sending the messages by hitting the database
    public void startSendingMessage()
    {

        if (!taskDone)
        {
            writeToLog("A Thread was already working on the same Priority.");
            return;
        }

        try
        {
        }
        catch (Exception ex)
        {
            writeToLog(ex.Message);
        }
        finally
        {
            taskDone = stopSendingMessage();

            //this will ensure that till the database update is not fine till then, it will not leave trying to update the DB
            while (!taskDone)//infinite looop will fire to ensure that the database is updated in every case
            {
                taskDone = stopSendingMessage();
            }
        }

    }


public bool stopSendingMessage()
    {
        bool smsFlagUpdated = true;
        try
        {

        }
        catch (Exception ex)
        {
            writeToLog(ex.Message);
        }
        return smsFlagUpdated;
    }

}
}

2
另一种做法是等待事件而不是使用定时器。
public class PollingService
{
    private Thread _workerThread;
    private AutoResetEvent _finished;
    private const int _timeout = 60*1000;
}

public void StartPolling()
{
    _workerThread = new Thread(Poll);
    _finished = new AutoResetEvent(false);
    _workerThread.Start();
}

private void Poll()
{
    while (!_finished.WaitOne(_timeout))
    {
        //do the task
    }
}

public void StopPolling()
{
    _finished.Set();
    _workerThread.Join();
}

为您服务

public partial class Service1 : ServiceBase
{
    private readonly PollingService _pollingService = new PollingService();
    
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _pollingService.StartPolling();
    }

    protected override void OnStop()
    {
        _pollingService.StopPolling();
    }
}

0

你可以使用计时器或专用的线程/任务来进行睡眠等操作。个人而言,我发现专用的线程/任务比计时器更容易处理这些事情,因为它更容易控制轮询间隔。此外,你应该一定要使用提供的协作取消机制 TPL。它不一定会抛出异常,只有在调用 ThrowIfCancellationRequested 时才会这样做。你可以使用 IsCancellationRequested 来检查取消令牌的状态。

以下是一个非常通用的模板,你可以用它来开始工作。

public class YourService : ServiceBase
{
  private CancellationTokenSource cts = new CancellationTokenSource();
  private Task mainTask = null;

  protected override void OnStart(string[] args)
  {
    mainTask = new Task(Poll, cts.Token, TaskCreationOptions.LongRunning);
    mainTask.Start();
  }

  protected override void OnStop()
  {
    cts.Cancel();
    mainTask.Wait();
  }

  private void Poll()
  {
    CancellationToken cancellation = cts.Token;
    TimeSpan interval = TimeSpan.Zero;
    while (!cancellation.WaitHandle.WaitOne(interval))
    {
      try 
      {
        // Put your code to poll here.
        // Occasionally check the cancellation state.
        if (cancellation.IsCancellationRequested)
        {
          break;
        }
        interval = WaitAfterSuccessInterval;
      }
      catch (Exception caught)
      {
        // Log the exception.
        interval = WaitAfterErrorInterval;
      }
    }
  }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接