statring后立即停止Windows服务

时间:2016-03-19 12:16:15

标签: c# windows-services

我写了一个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");
    }

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

enter image description here

任何人都可以帮助我......

2 个答案:

答案 0 :(得分:2)

Windows服务没有用户界面。因此,您无法显示服务中的消息框。如果要报告错误,标准方法是使用事件日志。

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

答案 1 :(得分:0)

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 ");

        }

我同意TSu​​ngur,仅通过事件日志(在我的代码中实现的一个地方)进行记录