Windows服务不断启动和停止

时间:2014-02-10 10:48:48

标签: c# windows-services

启动Windows服务时遇到此错误消息。

本地计算机上的服务已启动然后停止。如果某些服务未被其他服务和程序使用,则会自动停止。

我的代码:

     protected override void OnStart(string[] args)
     {
        string eventLogMessage = string.Format(@"Notify Service is starting :{0}", DateTime.Now);
        EventLogging.LogInformation(eventLogMessage);

            double interval;

            try
            {
                interval = Convert.ToDouble(ConfigurationManager.AppSettings["intervalInSeconds"]);
                EventLogging.LogInformation(
                    string.Format("Loaded configuration: Interval duration is {0} minutes", (interval / 60)));
            }
            catch (Exception exception)
            {
                interval = 3600;

                eventLogMessage = string.Format("Loading configuration failed: Interval duration is {0} minutes", (interval / 60));
                eventLogMessage += string.Format("\nMessage was: {0}", exception.Message);

                EventLogging.LogWarning(eventLogMessage);
            }

            interval = interval * 1000;

            _timer.Interval = interval;
            _timer.Elapsed += TimerTick;
            _timer.Start();

            eventLogMessage = string.Format(@"Notify service has started: {0}", DateTime.Now);
            EventLogging.LogInformation(eventLogMessage);

            var workerThread = new Thread(NotifyUsers) { IsBackground = true };
            workerThread.Start();

    }

    private void NotifyUsers()
    {
        var userBL = new UserBL();

        List<User> usersToBeMailed = userBL.GetAllUsersWhosePasswordsWillExpire();

        string eventLogMessage = string.Format("Number of users to be mailed is {0}", usersToBeMailed.Count);
        EventLogging.LogInformation(eventLogMessage);

        foreach (User user in usersToBeMailed)
        {
            userBL.MailUser(user);
        }
    }

    private void TimerTick(object sender, ElapsedEventArgs e)
    {
        var workerThread = new Thread(NotifyUsers) { IsBackground = true };
        workerThread.Start();
    }

    protected override void OnStop()
    {
        base.OnStop();

        string eventLogMessage = @"Password notify service has stopped: " + DateTime.Now;

        EventLogging.LogInformation(eventLogMessage);
    }


    protected override void OnPause()
    {
        base.OnPause();
        _timer.Stop();
        EventLogging.LogWarning("Paused");
    }

    protected override void OnContinue()
    {
        base.OnContinue();
        _timer.Start();
        EventLogging.LogInformation("Resumed");
    }
}

1 个答案:

答案 0 :(得分:0)

您必须至少有一个您的线程做某事而不是后台线程,以保持进程活着。运行OnStart代码的线程实际上不是您的一个线程,此外,您必须从OnStart返回才能被认为已成功启动。

这可能就像从Thread方法创建并运行新的OnStart一样简单,只需等待ManualResetEvent来自Set的{​​{1}}对象代码。

或者,找到一些有用的工作要做这个线程(但仍然使用事件对象来指示它何时应该关闭),或者替代的两个是 - 考虑这个代码是否属于服务。如果它只是定期醒来通知用户,为什么不使用计划任务呢?