简体   繁体   English

启动后立即停止 Windows 服务

[英]Windows service is stopped immediately after statring

I Wrote a windows service, you can find code below我写了一个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");
    }

after installing, i started it by manually.安装后,我手动启动它。 It is immediately closing showing following error.它立即关闭,显示以下错误。

在此处输入图片说明

Could anyone help me...谁能帮帮我...

Windows services have no user interface. Windows 服务没有用户界面。 So you cannot show a message box from a service.所以你不能显示来自服务的消息框。 If you want to report errors, the standard way is using event log.如果要报告错误,标准方法是使用事件日志。

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

Windows service must execute OnStart() in limited time, or is killed. Windows 服务必须在有限的时间内执行OnStart() ,否则将被终止。 How many seconds?几秒? I don't remember, look in MSDN.我不记得了,看看MSDN。 When service is killed in this scenario, not too much info is reported, maybe Your is killed by watchdog too?在这种情况下服务被杀死时,不会报告太多信息,也许您的看门狗也被杀死了?

If longer start-up is required I usually start new thread如果需要更长的启动时间,我通常会启动新线程

  protected override void OnStart(string[] args)
        {

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

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

            MyXxxxxStarter.LogInfo("Thread started ");

        }

I agree with TSungur, logging only by event log (in my code implemented in one place)我同意 TSungur,仅通过事件日志记录(在我的代码中在一个地方实现)

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

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