.Net Windows 服务无法运行

发布于 2024-11-02 12:14:36 字数 4076 浏览 0 评论 0原文

我正在开发一个可自行安装的 Windows 服务。我有一个 ServiceManager 类来处理安装/卸载,并且似乎工作正常。

但是,当我尝试运行启动服务时,我立即收到一个包含以下文本的 MessageBox:

无法在本地启动服务 系统。错误 1053:服务未响应 启动或控制请求 及时时尚。

我的服务代码:

public partial class MyService : ServiceBase
{
    public MyService()
    {
        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test1");
            tw.Close();
        }
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {

        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test2");
            tw.Close();
        }

        Thread t = new Thread(new ThreadStart(InitService));
        t.Start();
    }

    protected override void OnStop()
    {
    }

    static void InitService()
    {
        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test4");
            tw.Close();
        }

        while (true)
        {
            Thread.Sleep(100);
        }
    }

设计器代码:

namespace MyService
{
    partial class MyService
    {
        /// <summary> 
        /// Variable del diseñador requerida.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Limpiar los recursos que se estén utilizando.
        /// </summary>
        /// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Código generado por el Diseñador de componentes

        /// <summary> 
        /// Método necesario para admitir el Diseñador. No se puede modificar 
        /// el contenido del método con el editor de código.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "MyService";
        }

        #endregion
    }
}

我的主要:

public static void Main(string[] args)
{
    try
    {
        bool debug = false;
        bool mustRun = false;
        string errMsg = "";
        mustRun = true;

        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test3");
            tw.Close();
        }

        ServiceManager manager = new ServiceManager();

        mustRun = !manager.ParseArgs(args, ref debug, ref errMsg);

        MyService svc = new MyService();

       //  
       //             if (debug)
       //             {
       //                 svc.DebugStart();
       //             } 
       //             else 
        if (mustRun)
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun = null;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { svc };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
        else
        {
        }
    }
    catch (Exception ex)
    {
        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine(ex.Message);
            tw.Close();
        }
    }
}

文件 C:\Test.txt 不会写入,除非安装或卸载服务(使用 Test3 字符串)。我使用的是Windows XP,所以应该不会有权限问题。

我尝试使用 System 和 NetworkService 帐户安装服务,但出现了同样的问题。

使用管理员帐户,它给了我另一个与该帐户相关的错误(我想这是因为我没有密码)。

知道会发生什么吗?

更新:回答David的问题,事件日志是这样说的(手工翻译,英文消息可能会有所不同):

服务无法启动。服务 进程无法与服务连接 控制器。

更新 2: 更仔细地查看 Applicatin 日志,发现之前的错误是由于服务安装名称与设计器中的 ServiceName 属性不匹配造成的。事情已经解决了;现在事件日志中没有新的错误,但问题仍然存在。

I am developing a self-installable Windows Service. I have a ServiceManager class that handles the installation / uninstallation, and seems to work correctly.

However, when I try to run the start the service I get, immediately, a MessageBox with the following text:

Could not start service on local
system. Error 1053: The service didn't respond to
the start or control request in a
timely fashion.

My Service code:

public partial class MyService : ServiceBase
{
    public MyService()
    {
        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test1");
            tw.Close();
        }
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {

        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test2");
            tw.Close();
        }

        Thread t = new Thread(new ThreadStart(InitService));
        t.Start();
    }

    protected override void OnStop()
    {
    }

    static void InitService()
    {
        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test4");
            tw.Close();
        }

        while (true)
        {
            Thread.Sleep(100);
        }
    }

The designer code:

namespace MyService
{
    partial class MyService
    {
        /// <summary> 
        /// Variable del diseñador requerida.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Limpiar los recursos que se estén utilizando.
        /// </summary>
        /// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Código generado por el Diseñador de componentes

        /// <summary> 
        /// Método necesario para admitir el Diseñador. No se puede modificar 
        /// el contenido del método con el editor de código.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "MyService";
        }

        #endregion
    }
}

My Main:

public static void Main(string[] args)
{
    try
    {
        bool debug = false;
        bool mustRun = false;
        string errMsg = "";
        mustRun = true;

        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine("Test3");
            tw.Close();
        }

        ServiceManager manager = new ServiceManager();

        mustRun = !manager.ParseArgs(args, ref debug, ref errMsg);

        MyService svc = new MyService();

       //  
       //             if (debug)
       //             {
       //                 svc.DebugStart();
       //             } 
       //             else 
        if (mustRun)
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun = null;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { svc };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
        else
        {
        }
    }
    catch (Exception ex)
    {
        using (TextWriter tw = new StreamWriter(path: "C:\\Test.txt", append: true))
        {
            tw.WriteLine(ex.Message);
            tw.Close();
        }
    }
}

File C:\Test.txt isn't written to, except when installing or uninstalling the service (With Test3 string). I'm using Windows XP so there shouldn't be permission problems.

I have tried installing the service with the System and NetworkService account, and the same problem arises.

With the administrator account it gives me another error, related to the account (I guess it's because I don't have a password).

Any idea about what happens?

Update: Answering David's question, this is what the event log says (hand translation, the english message could be different):

The service cannot start. The service
process cannot connect with the service
controller.

Update 2: Looking more carefully to the Applicatin log, the previous error was due to a mismatch between the Service installation name and the ServiceName property in the designer. It was already fixed; now there aren't new errors in the event log but the problem persists.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

擦肩而过的背影 2024-11-09 12:14:36

从表面上看,您需要启动运行该服务的线程。

Thread t = new Thread(new ThreadStart(InitService));
t.Start();

From the looks of it you need to start the thread that runs the service.

Thread t = new Thread(new ThreadStart(InitService));
t.Start();
你对谁都笑 2024-11-09 12:14:36

您提到在安装或卸载服务时文本“Test3”被写入文件。不要将“Test3”写入文件,而是写入 tw.WriteLine(ex.Message); 来查看具体的异常是什么。

You mention that the text "Test3" is being written to the file when installing or uninstalling the service. Rather than writing "Test3" to the file, write tw.WriteLine(ex.Message); to see what the specific exception is.

难得心□动 2024-11-09 12:14:36

我终于找到问题所在了。

它位于ServiceManager中;当我从 IDE 安装服务时,它获取的可执行文件名称为 MyService.vshost.exe,而不是 MyService.exe。

我通过以下链接找到了此阅读内容

http://www.c-sharpcorner.com/UploadFile/timosten/DynamicServiceInCSharp11262005062503AM/DynamicServiceInCSharp.aspx

查看它正在写入的注册表项:

//Open the HKEY_LOCAL_MACHINE\SYSTEM key
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
//Go to the services key
services = currentControlSet.OpenSubKey("Services");

非常感谢所有试图提供帮助的人。

I have finally found the problem.

It lies in the ServiceManager; as I was installing the service from the IDE, it was getting the executable name as MyService.vshost.exe instead of MyService.exe.

I found this reading through the following link,

http://www.c-sharpcorner.com/UploadFile/timosten/DynamicServiceInCSharp11262005062503AM/DynamicServiceInCSharp.aspx

looking the registry keys it was writing:

//Open the HKEY_LOCAL_MACHINE\SYSTEM key
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
//Go to the services key
services = currentControlSet.OpenSubKey("Services");

Thank you a lot to everyone who tried to help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文