在Windows服务中使用计时器

时间:2012-04-04 15:18:17

标签: c# multithreading windows-services timer

我想在Windows服务中使用计时器而不是睡眠,该服务应该以恒定的间隔执行操作。

假设我有以下课程。

class MailManagerClient
{

    //fields
    string someString

    //Constructor
    public MailManagerClient()
    { 
          aTimer = new System.Timers.Timer(30000);
          aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
          aTimer.Enabled = true
    }
    //methode

    public bool DoSomthingIncConstantInterval()
    {
        //Do Somthing
        return true;
    }


    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
       DoSomthingIncConstantInterval()
    }
}

我还有一个使用OnStart方法的Windows服务。

我理解在OnStart方法中,我需要为MailManagerClient类型启动一个新线程。

但是如何启动线程呢?哪个方法应该是新线程的入口点?

该线程应如何保持活力?

3 个答案:

答案 0 :(得分:1)

在OnStart方法中,你可以 -

MailManagerClient m;
var th = new Thread(()=>m=new MailManagerClient());
th.Start();

答案 1 :(得分:1)

因为你在构造函数中启动计时器而不是你真正需要做的就是在MailManagerClient中实例化一个OnStart。您不需要手动创建线程,因为System.Timers.TimerElapsed的线程上执行ThreadPool事件处理程序。

public class MyService : ServiceBase
{
  private MailManagerClient mmc = null;

  protected void OnStart(string[] args)
  {
    mmc = new MailManagerClient();
  }

}

我应该指出,对于下一个查看代码的程序员来说MailManagerClient.ctor实际上正在做什么事情并不明显。最好定义一个Start方法或类似的启用内部计时器的方法。

答案 2 :(得分:1)

您也可以考虑定义Windows任务,如本答案中所述:What is the Windows version of cron?。 Windows操作系统将负责调度和线程化。