Windows服务在启动后立即停止

本文关键字:服务 启动 Windows | 更新日期: 2023-09-27 18:21:47

我在编写windows服务时遇到以下问题:当我启动服务时,它会立即停止。当我使用控制台应用程序时,它并不令人崩溃。我不知道这个问题的原因是什么。

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration;
using System.Configuration.Install;
using WindowsService;
namespace WS
{
    [ServiceContract(Namespace = "http://WS")]
    public interface INewsReader
    {
    }

    public class NewsReaderService : INewsReader
    {
        public NewsReaderService()
        {
            var config = new Config();
            var scheduled = new Schedule(config);
            scheduled.ExecuteScheduledEvents();
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                int i = 0;
            }
        }
    }
    public class NewsReaderWindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;
        public NewsReaderWindowsService()
        {
            ServiceName = "NewsReaderWindowsService";
        }
        public static void Main()
        {
            ServiceBase.Run(new NewsReaderWindowsService());
        }

        protected override void OnStart(string[] args)
        {
            var thread = new System.Threading.Thread(() =>
            {
                while (true)
                {
                    int i = 0;
                    System.Threading.Thread.Sleep(1000);
                }
            });
            thread.Start();
            serviceHost = new ServiceHost(typeof(NewsReaderService));

            serviceHost.Open();
        }
        protected override void OnStop()
        {
        }
    }

    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;
        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = "NewsReaderWindowsService";
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}

Windows服务在启动后立即停止

首先,我认为您的OnStart方法写得很糟糕。我看不出创建一个基本上是空线程的原因。您应该只初始化服务(如有必要),立即启动一个将一直工作的新线程,并离开OnStart方法。

其次,使用try-catch块,因为在我看来,其中的某个地方出现了异常,这就是您的windows服务停止的原因。

第三,请参阅此示例WCF Hosting with Windows Service