0

我尝试创建一个自动启动的 Windows 服务。我能够安装和卸载该服务。如果我尝试启动它,我会收到以下错误消息:“Der Dienst antwortete nicht rechtzeitig auf die Startoder Steueranfrage”。(我试着翻译)“服务没有及时响应启动或控制请求”。

这是我糟糕的代码

    public class LisaServerService: System.ServiceProcess.ServiceBase
{
    private Program lisaServerServiceProgram;

    public static string LisaServiceName = "LISA-ServerService";

    [STAThread]
    public static void Main(string[] args)
    {
        LisaServerService lisaServerService = new LisaServerService();

        if (Environment.UserInteractive)
        {
            lisaServerService.OnStart(args);
            Console.WriteLine("I am a service. Normally you can't see the console... just ignore me");
            Console.ReadLine();
            lisaServerService.OnStop();
        }
        else
        {
            ServiceBase.Run(lisaServerService);
        }
    }

    public LisaServerService()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        this.CanShutdown = true;
        this.ServiceName = "LISA - ServerService";
        this.CanPauseAndContinue = true;
        this.lisaServerServiceProgram = new Program();
    }

    protected override void OnStart(string[] args)
    {
        lisaServerServiceProgram.Start(null);
        base.OnStart(args);
    }

    protected override void OnStop()
    {
        lisaServerServiceProgram.Stop();
        base.OnStop();
    }

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

程序.cs

    public class Program
{
    public Program()
    {
        Logger.LogLevel = LogLevel.Information;
        Logger.LogRange = LogRange.Write;
        Logger.Log("Logger initialized");
    }

    public void Start(string[] args)
    {
        DatabaseHandler.StartDatabase();
        NetworkHandler.StartNetwork();
        Logger.Log("Service started");
    }

如果我将服务作为控制台程序运行,它工作正常。所以数据库连接+记录器也工作正常。(同样在 < 10 毫秒内)

4

1 回答 1

1

如果您在交互模式下运行服务,它会在此处等待控制台:

if (Environment.UserInteractive)
{
    lisaServerService.OnStart(args);
    Console.WriteLine("I am a service. Normally you can't see the console... just ignore me");
    Console.ReadLine();
    ...

这可能会阻止服务正确响应以指示它已启动。

于 2013-09-04T20:19:21.520 回答