问题描述
我创建了一个具有 OnStart
方法的 Windows 服务应用程序.该方法将从 app.config 文件中读取路径,创建一个对象,然后服务将对象的重写 ToString()
方法写入带有 的文件StreamWriter
.
I have created a windows service app which has OnStart
method. The method will read a path from the app.config file, create an object, then the service write the object's overridden ToString()
method to a file with a StreamWriter
.
当我使用net start"手动启动此服务时,这是有效的.因此,OnStart
方法调用,对象创建并将其 ToString
方法写入文件.
This is working when I manually start this service with "net start". So the OnStart
method called, object created and written its ToString
method to a file.
我将其设置为 Windows 启动时自动运行的服务.我的问题是,在 Windows 启动服务后不会调用此 OnStart
方法.所以我认为当 Windows 在启动时开始运行服务时,它会启动我的服务,只是不要调用 OnStart
方法.
I set it as an automatic running service, when the Windows starts up.My problem is, that this OnStart
method is not called after the service is being started by Windows. So I think when the windows starts running the services at start up, it launches my service just don't calling the OnStart
method.
有没有人遇到同样的问题或有人有解决方案?
Does anybody have the same issue or somebody have a solution for it?
OnStart 方法:
OnStart method:
protected override void OnStart(string[] args)
{
filePath = configReader.ReadConfig("FilePath");
DateEvent dateEvent = new DateEvent(DateTime.Now, TimeLoggerCore.Events.STARTUP.ToString());
writer.WriteToFile(dateEvent, filePath, true, false);
}
构造函数:
public TimeLoggerService()
{
InitializeComponent();
configReader = new AppConfigReader();
writer = new CSVWriter();
}
Program.cs:
Program.cs:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TimeLoggerService()
};
ServiceBase.Run(ServicesToRun);
}
推荐答案
如果事件查看器显示服务已成功启动,则您的 OnStart 已被调用并已从中返回.你是如何确定它没有被调用的?我猜是因为您的文件尚未写入.问题可能不是您的 OnStart 没有被调用,而是 WriteToFile 失败和/或它被写入不同的位置(例如,您使用的相对路径在启动期间不同或不可用).我建议按照以下程序进行检查:
If the event viewer shows that the service was started successfully, your OnStart has been called and has been returned from. How did you determine that is was not called? I guess by the fact that your file has not been written to. The problem is likely not that your OnStart is not called but that the WriteToFile failed and/or it was written to a different location (e.g. you use a relative path which is different or unavailable during startup). I suggest the following procedure to check this:
- 使用 System.Diagnostics.Trace.WriteLine 在 OnStart 中输出调试消息
- 从 Microsoft 下载并安装/复制 DebugView 应用程序.
- 将 DebugView 配置为 1) 捕获全局 Win32,2) 使用您的应用程序名称设置进程名称过滤器,以及 3) 在启动时启用日志记录(请参阅 DebugView 帮助).
对所有设置进行一些实验,以确保它们按预期工作.
Experiment a bit with all setting to make sure they work as intended.
最后,还要注意 OnStart 中的此注释文档:
不要使用构造函数来执行应该在 OnStart 中的处理.使用 OnStart 处理服务的所有初始化.构造函数在应用程序的可执行文件运行时调用,而不是在服务运行时调用.可执行文件在 OnStart 之前运行.例如,当您继续时,不会再次调用构造函数,因为 SCM 已将对象保存在内存中.如果 OnStop 释放在构造函数中分配的资源而不是在 OnStart 中分配的资源,则第二次调用服务时将不会再次创建所需的资源.
这篇关于为什么 Windows 服务不调用 OnStart 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!