简体   繁体   English

Windows Service不断启动和停止

[英]Windows Service keeps starting and stopping

Kept on encountering this error message when starting my Windows Service. 继续在启动Windows服务时遇到此错误消息。

The service on local computer started and then stopped. 本地计算机上的服务已启动,然后停止。 Some services stop automatically if they are not in use by other services and programs. 如果某些服务未被其他服务和程序使用,则会自动停止。

My codes: 我的代码:

     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");
    }
}

You have to have at least one of your threads doing something and not being a background thread, to keep the process alive. 你必须有你的线程中的至少一个什么事情而不是后台线程,以保持工艺活。 The thread that the OnStart code runs on isn't really one of your threads, and besides, you have to return from OnStart in order to be considered to have successfully started. 运行OnStart代码的线程实际上不是您的线程之一,此外,您必须从OnStart返回才能被视为已成功启动。

This could be as simple as creating and running a new Thread from your OnStart method that just waits on a ManualResetEvent object that you Set from your OnStop code. 这就像从OnStart方法创建并运行新Thread一样简单,该方法仅等待您从OnStop代码中SetManualResetEvent对象。

Alternatively, find some useful work for this thread to do (but still use the event object to signal when it should shut down), or alternative two is - consider whether this code belongs in a service at all. 或者,找到一些有用的工作来使线程执行此操作(但仍使用事件对象来指示何时应关闭该事件),或者,另外两个选择是-考虑此代码是否完全属于服务。 If it's just waking periodically to notify users, why not use a scheduled task instead? 如果只是定期唤醒以通知用户,为什么不使用计划任务呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM