如何在Windows服务中每天检查许可证

时间:2012-09-16 18:44:16

标签: c# windows-services

  

可能重复:
  Use DispatcherTimer with Windows Service

我想在我的Windows服务中每天查看许可证 我尝试使用DispatcherTimer但不起作用 这就是我试图做的事情

 public OIMService()
    {
        InitializeComponent();
        _dispatcherTimer = new DispatcherTimer();
        this.ServiceName = "OIMService";
        if (!System.Diagnostics.EventLog.SourceExists("OIM_Log"))
        {
            EventLog.CreateEventSource("OIM_Log", "OIMLog");
        }
        EventLog.Source = "OIM_Log";
        EventLog.Log = "OIMLog";
        _sc = new ServiceController("OIMService");
        _helpers = new ValidationHelpers();
        StartTimer();

    }

  private void StartTimer()
        {
            _dispatcherTimer.Tick += new EventHandler(DispatcherTimerTick);
            _dispatcherTimer.Interval = new TimeSpan(0, 0, Convert.ToInt32(time));
            _dispatcherTimer.IsEnabled = true;
            _dispatcherTimer.Start();
        }

    private void DispatcherTimerTick(object sender, EventArgs e)
    {
        var helpers  = new ValidationHelpers();
        if (!helpers.IsValid())
            this.Stop();

    }

1 个答案:

答案 0 :(得分:1)

您可以使用这样的新主题:

    bool cancelJob = false;

    ThreadStart ts = new System.Threading.ThreadStart(CheckLicence);
    Thread thMain = new System.Threading.Thread(ts);
    thMain.Start();


    void CheckLicence()
    {
        //you can use cancelJob to break the thread...
        while (!this.cancelJob)
        {
            //TODO: code to check your licence...

            //sleep for 1 hour...
            System.Threading.Thread.Sleep(3600000);
        }
    }

如果要停止服务,请确保也终止该线程,如下所示:

        thMain.Abort();
相关问题