本地计算机上的服务启动然后停止.如果其他服务或程序未使用某些服务,则它们会自动停止 [英] The service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs

查看:34
本文介绍了本地计算机上的服务启动然后停止.如果其他服务或程序未使用某些服务,则它们会自动停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
    private ServiceProcessInstaller serviceProcessInstaller;
    private ServiceInstaller serviceInstaller;

    public ProjectInstaller()
    {
        serviceProcessInstaller = new ServiceProcessInstaller();
        serviceInstaller = new ServiceInstaller();
        // Here we can set properties on serviceProcessInstaller
        //or register event handlers
        serviceProcessInstaller.Account = ServiceAccount.LocalService;

        serviceInstaller.ServiceName = MyNewService.MyServiceName;
        this.Installers.AddRange(new Installer[] {
            serviceProcessInstaller, serviceInstaller });
    }

    private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {

    }
}



public partial class MyNewService : ServiceBase
{

    FileSystemWatcher myWatcher = new FileSystemWatcher("C:\\Users\\Ahmed\\Desktop\\demo");
    public const string MyServiceName = "MyNewService";
    private FileSystemWatcher watcher = null;


    public MyNewService()
    {
        InitializeComponent();
        myWatcher.NotifyFilter = NotifyFilters.LastAccess
           | NotifyFilters.LastWrite
           | NotifyFilters.FileName
           | NotifyFilters.DirectoryName;
    }
    //private static void OnChanged(object source, FileSystemEventArgs e)
    //{

    //    WatcherChangeTypes wct = e.ChangeType;
    //    Console.WriteLine("File {0} {1}", e.FullPath, wct.ToString());
    //}
    protected void FileCreated(object sender, FileSystemEventArgs e)
    {
        if (e.ChangeType == WatcherChangeTypes.Created)
        {
            if (Directory.Exists(e.FullPath))
            { Console.WriteLine("Directory Exists"); }            // a directory
            else { Console.WriteLine("File"); }
            // a file
        }
    }


    protected override void OnStart(string[] args)
    {

        this.ServiceName = MyServiceName;


        FileSystemWatcher watcher = new FileSystemWatcher("C:\\Users\\Ahmed\\Desktop\\demo", "*.txt");

        //Watch for changes in LastAccess and LastWrite times, and
        //the renaming of files or directories.
        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);

        // Begin watching.
        watcher.EnableRaisingEvents = true;
    }

    protected override void OnStop()
    {
        watcher.EnableRaisingEvents = false;
        watcher.Dispose();

        LogEvent("Monitoring Stopped");
    }

    void OnChanged(object sender, FileSystemEventArgs e)
    {
        string mgs = string.Format("File {0} | {1}",e.FullPath, e.ChangeType);
        LogEvent(mgs);
    }

    void OnRenamed(object sender, RenamedEventArgs e)
    {
        string log = string.Format("{0} | Renamed from {1}",
                                   e.FullPath, e.OldName);
        LogEvent(log);
    }
    private void LogEvent(string message)
    {
        string eventSource = "File Monitor Service";
        DateTime dt = new DateTime();
        dt = System.DateTime.UtcNow;
        message = dt.ToLocalTime() + ": " + message;

        EventLog.WriteEntry(eventSource, message);
    }

    private void eventLog1_EntryWritten(object sender, EntryWrittenEventArgs e)
    {

    }
}


static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new MyNewService() 
        };
        ServiceBase.Run(new ServiceBase[] { new MyNewService() });
    }
}

推荐答案

这里的问题是 this.ServiceName = MyServiceName; 应该在构造函数中,而不是在 OnStart 方法中.构造函数将为每个实例设置它,但它会抛出异常,因为在调用 OnStart 时该服务已被视为正在运行.

The problem here is that this.ServiceName = MyServiceName; should be in the Constructor, not the OnStart method. The constructor will set it for each instance, but it throws an exception because the service is already considered running by the time OnStart is called.

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

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 参考

这篇关于本地计算机上的服务启动然后停止.如果其他服务或程序未使用某些服务,则它们会自动停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆