【问题标题】:C# Windows service not startingC# Windows 服务未启动
【发布时间】:2013-09-04 20:13:51
【问题描述】:

我尝试创建一个自动启动的 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");
    }

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

【问题讨论】:

  • Program 和 LisaServerService 的构造函数是什么样的?
  • 我会说你的 OnStart 方法永远不会返回......是吗?
  • 事件查看器有什么提示吗?
  • 可能运行服务的凭据不足以访问数据库?我也觉得将服务本身与主要功能分开是最佳实践。
  • 您是否尝试过设置断点并查看它是否在某处抛出异常?

标签: c# service windows-services


【解决方案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();
    ...

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

【讨论】:

  • 我删除了这些行,但结果相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多