简体   繁体   English

Windows Service在安装后未运行

[英]Windows Service not running after installing

I have created a windows service to send mail when service is started. 我创建了Windows服务,以便在服务启动时发送邮件。 The service works fine like it sends mail when i debug the service and run it via code. 该服务工作正常,就像我调试服务并通过代码运行它时发送邮件一样。 But the service is not working after i install it. 但是我安装它后该服务无法正常工作。 It is not sending any mail after i install the service. 我安装该服务后没有发送任何邮件。

Can anyone please suggest me the solution? 谁能建议我解决方案?

There is an excellent chance that the service lacks permission to perform one or more actions when run as a service account. 当作为服务帐户运行时,服务极有可能缺少执行一项或多项操作的权限。

Check the Windows Event Log for any related error messages. 检查Windows事件日志中是否有任何相关的错误消息。 As a test, you can configure your service to run as the same user you log on with (just to make sure the issue is permission based... do NOT leave that configuration active as it is a major security hole). 作为测试,您可以将服务配置为以登录时使用的同一用户身份运行(只是确保问题是基于权限的,因此不要将该配置保持活动状态,因为这是一个重大的安全漏洞)。

Debugging service is a bit difficult. 调试服务有点困难。 use try..catch block with writing messages to file in every method; 使用try..catch块以每种方法将消息写入文件; for example 例如

try
{
    ..
}
catch(Exception ex)
{
    SaveMessage(ex.ToString());
}

Save message method would be: 保存消息的方法是:

static void SaveMessage(string s)
{
    StreamWriter sw = new StreamWriter(@"C:\service_exceptions_file.txt", true);
    sw.WriteLine(s);
    sw.Close();
}        

Then you will see where is the problem. 然后,您将看到问题出在哪里。

Also you can add some messages in your code via abovementioned method to see what parts of code are working without problems 您也可以通过上述方法在代码中添加一些消息,以查看代码的哪些部分正常工作

In your Main() method, just add the following lines before ServiceBase.Run(ServicesToRun); 在您的Main()方法中,只需在ServiceBase.Run(ServicesToRun);之前添加以下行ServiceBase.Run(ServicesToRun); :

#if DEBUG
            while(!Debugger.IsAttached)
            {
                Thread.Sleep(1000);
            }
#endif

Then install your service and launch it. 然后安装您的服务并启动它。 While it's launching, attach your debugger to your service's process (Debug Menu => Attach to process) and you should be able to debug it. 启动时,将调试器附加到服务的进程(Debug Menu => Attach to process),您应该可以对其进行调试。

Don't forget to set your breakpoints before launching your service. 启动服务之前,请不要忘记设置断点。

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

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