如果某些服务未被其他服务使用,则会自动停止

par*_*shi 20 c# windows service windows-services

在尝试启动Windows服务时,错误"某些服务会自动停止,如果它们不被其他服务使用".

我有一个不使用Windows服务配置文件并使用静态属性的服务 - 它工作正常

现在,我使用app.config文件并重建我的安装项目+服务项目.现在我安装该服务,然后尝试启动该服务 - 我收到以下错误:

如果不使用其他服务,某些服务会自动停止

服务以本地系统登录.

欢迎任何意见!谢谢.

Mat*_*vis 39

这通常是两件事之一的结果 - (a)您的OnStart()方法抛出异常或(b)该OnStart()方法没有开始执行工作.

如果问题是(a),那么显而易见的解决方案是调试服务以识别出错的地方.至少,try-catchOnStart()方法内容周围放置一个块,并在发生异常时将错误记录到系统事件日志中.然后,您可以在Windows事件查看器中查看详细信息.

如果问题是(b),那么你需要创建一个实际做某事的线程.线程需要是前台线程(而不是后台线程)以防止服务关闭.典型的OnStart()方法如下所示:

private System.Threading.Thread _thread;

protected override void OnStart(string[] args)
{
    try
    {
        // Uncomment this line to debug...
        //System.Diagnostics.Debugger.Break();

        // Create the thread object that will do the service's work.
        _thread = new System.Threading.Thread(DoWork);

        // Start the thread.
        _thread.Start();

        // Log an event to indicate successful start.
        EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);
    }
    catch (Exception ex)
    {
        // Log the exception.
        EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
    }
}

private void DoWork()
{
    // Do the service work here...
}
Run Code Online (Sandbox Code Playgroud)