我正在使用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;应该在构造函数中,因为似乎有必要对其进行设置。


  ServiceName向服务控制管理器标识服务。此属性的值必须与相应安装程序类的ServiceInstaller.ServiceName属性中为服务记录的名称相同。在代码中,通常在可执行文件的main()函数中设置服务的ServiceName。


-MSDN Reference

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

10-11 08:29