gpt4 book ai didi

c# - Windows 服务在 SCM 中启动时无法解释地停止

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:13 25 4
gpt4 key购买 nike

我正在使用 C# 在 Visual Studio 中制作 Windows 服务。当我从命令行运行程序时,它按预期工作。没有异常被抛出或类似的东西,并且事件日志被写入正常。这是我的入口方法。

var service = new CSFolderWatcher();
if (Environment.UserInteractive)
{
service.CallStart(args);
Console.WriteLine("Press enter to stop program");
Console.Read();
service.CallStop();
}
else
{
ServiceBase.Run(new ServiceBase[] { new CSFolderWatcher() });
}

但是,当我进入 SCM 启动服务时,立即弹出一个框,上面写着“本地计算机上的 CS Folder Watcher 服务已启动然后停止。某些服务如果未被其他服务使用则自动停止或程序。”根本没有任何内容写入事件日志。这是我的 onStart 代码:

internal void CallStart(string[] args) { OnStart(args); }
internal void CallStop() { OnStop(); }
protected override void OnStart(string[] args)
{
this.ServiceName = MyServiceName;

Properties.Settings.Default.Reload();
this.destfolder = Properties.Settings.Default.DestinationFolder;
this.watchfolder = Properties.Settings.Default.WatchFolder;
this.watchfilter = Properties.Settings.Default.WatchFilter;
LogEvent(this.ServiceName + " starting" + "\r\n" +
"Destination folder: " + this.destfolder + "\r\n" +
"Watch Folder: " + this.watchfolder + "\r\n" +
"Watch Filter: " + this.watchfilter + "\r\n" +
"OnStart args: " + string.Join(", ", args));

// Create a new FileSystemWatcher with the path
//and text file filter
try { watcher = new FileSystemWatcher(watchfolder, watchfilter); }
catch (Exception e) { LogEvent(e.ToString()); throw; }

watcher.IncludeSubdirectories = Properties.Settings.Default.WatchSubdirectories;
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;

// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
}

这是 LogEvent 的代码:

private void LogEvent(string message)
{
string eventSource = MyServiceName;
DateTime dt = new DateTime();
dt = System.DateTime.UtcNow;
message = dt.ToLocalTime() + ": " + message;

Console.WriteLine(message);
EventLog.WriteEntry(eventSource, message);
}

最佳答案

问题原来是您无法通过 OnStart 方法设置 ServiceName 属性。 this.ServiceName = MyServiceName; 应该放在构造函数中,因为它似乎 有必要设置它。

The ServiceName identifies the service to the Service Control Manager. The value of this property must be identical to the name recorded for the service in the ServiceInstaller.ServiceName property of the corresponding installer class. In code, the ServiceName of the service is usually set in the main() function of the executable.

-- MSDN Reference

关于c# - Windows 服务在 SCM 中启动时无法解释地停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com