睡眠窗口服务直到线程计时器启动

时间:2013-11-27 09:37:11

标签: c# multithreading windows-services

我正在创建一个Windows服务来运行一些间隔的任务。在这里,用户可以设置任务开始时间(第一次运行)和任务间隔。在OnStart事件的程序中,设置计时器并等待触发器。

但问题是主线程在线程计时器启动之前死掉了。所以我尝试添加Thread.CurrentThread.Join()Sleep()直到计时器开始。但是在我安装Windows服务后,我无法启动Windows服务,因为sleepblock处于OnStart事件中。所以它卡住了,或者睡了很长时间并且显示出一些异常。

我需要的就是停止退出主线程直到线程计时器触发器。

  public partial class Service1 : ServiceBase
  {
    TimerCallback timer_delegate;
    Timer houskeep_timer;

   protected override void OnStart(string[] args)
    {
      SettingReader settings = new SettingReader();
      if (settings.init())
      {
        timer_delegate = new TimerCallback(houseKeep);
        houskeep_timer = new Timer(timer_delegate, "testing", 33333100000, 44450000);
        //Thread.CurrentThread.Join();
      }
    }

     private void houseKeep(object setting_obj)
    {
        string message = (string)setting_obj;
        writeToLogFile(message);
    }   
}

3 个答案:

答案 0 :(得分:2)

我不会使用计时器,我会使用普通的exe并在任务调度程序中设置它。否则,您只是实现自己的调度,而且内置于Windows中的功能要少得多。

请参阅Jon Galloway post,了解为何不使用服务来运行计划任务。

答案 1 :(得分:0)

请注意,这不是执行多线程处理的最佳方法,但它可能是解决您问题的方法 使用一个对于踏板是全局的布尔变量。将它设置在主踏板上,看它是否发生变化!当您希望主线程退出时,在服务步骤中更改它。之后主线程将在您想要的时间退出。只要您在踏板之间创建的标记为invoke,就无需执行任何bool方法或其他方法。

答案 2 :(得分:0)

这将实现您的需求

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        private System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false);

        protected override void OnStart(string[] args)
        {
            new System.Threading.Thread(mt) { IsBackground = true }.Start();
        }

        private void mt()
        {
            // Set up timer here

            // wait for OnStop indefinitely
            are.WaitOne();
        }

        protected override void OnStop()
        {
            are.Set();
        }
    }
}

OnStart将启动一个无限期等待OnStop的线程。在这个帖子中,你将创建你的计时器。

相关问题