Windows服务启动后立即停止

Windows service is stopped immediately after statring

我写了一个windows服务,你可以在下面找到代码

    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new AutoUpgradeServiceDemo()
        };
        ServiceBase.Run(ServicesToRun);

    }

//Service class
    public AutoUpgradeServiceDemo()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        MessageBox.Show("Service Has been Started");
        //My logic goes here
    }

    protected override void OnStop()
    {
        //My logic goes here
        MessageBox.Show("Service Has been Stopped");
    }

安装后,我手动启动了它。它立即关闭并显示以下错误。

谁能帮帮我...

Windows 服务没有用户界面。所以你不能显示来自服务的消息框。如果要报告错误,标准方法是使用事件日志。

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    //my stuff
    this.WriteEventLogEntry("My service started successfully", System.Diagnostics.EventLogEntryType.Information);
}

Windows 服务必须在限定时间内执行 OnStart(),否则将被终止。 多少秒?不记得了,去msdn看看。 在这种情况下服务被杀死时,没有报告太多信息,也许你也被看门狗杀死了?

如果需要更长时间的启动,我通常会启动新线程

  protected override void OnStart(string[] args)
        {

            MyXxxxxStarter.LogInfo("Try to start thread");

            worker = new Thread(WorkerThread);
            worker.Start();

            MyXxxxxStarter.LogInfo("Thread started ");

        }

我同意 TSungur 的观点,仅通过事件日志记录(在我的代码中在一个地方实现)