Windows 用 C# 实现的服务没有在任务管理器/服务中启动

Windows Service implemented in C # does not start in the task manager / services

我正在用 C# 实现 Windows 服务,Visual Studio 2010 IDE。

我首先尝试制作一个带有定时器的小应用程序,每 5 秒写入一个文件并且运行良好。服务好,一切从头开始。

经过这次测试,我需要的是制作一个写入文件"USB memory is entered"和"remove USB memory"的服务。我记录了我进入记忆的次数。

这是我的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
using System.Management;
using System.Threading.Tasks;
using System.Threading;

namespace Test
{
      public partial class Service1 : ServiceBase 
      {   
        System.Timers.Timer tim = null;     
        public Service1()
        {
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
            /* tim = new System.Timers.Timer();
            tim.Interval = 5000;
            tim.Elapsed += new ElapsedEventHandler(tim_Elapsed); */ 
        }

        /*void tim_Elapsed(object sender, ElapsedEventArgs e)
        {
            TextWriter text = new StreamWriter(@"C:\log.txt", true);            
            text.WriteLine(DateTime.Now.ToString());
            text.Close();               
        }   */

        private void WriteFile(string que)
        {
            TextWriter text = new StreamWriter(@"C:\log.txt", true);
            text.WriteLine(que);
            text.Close();  
        }

        protected override void OnStart(string[] args)
        {
            tim.Start();          
        }

        protected override void OnStop()
        {
            tim.Stop();
        }

        private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
            foreach (var property in instance.Properties)
            {
                Console.WriteLine(property.Name + " = " + property.Value);
            }
            WriteFile("USB memory is entered");
        }

        void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
            foreach (var property in instance.Properties)
            {
                Console.WriteLine(property.Name + " = " + property.Value);
            }
            WriteFile("remove USB memory");
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

            ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
            insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
            insertWatcher.Start();

            WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
            ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
            removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
            removeWatcher.Start();            
            System.Threading.Thread.Sleep(20000000);
        }
    }
}

事实是,当服务到达任务管理器/服务时,总是停止,你右键单击并启动,并保持停止。

如果计时器工作正常而我只是因为这段代码没有启动? 我能有那个问题吗?有什么想法吗?问候

查看 OnStart 的文档:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

所以听起来您需要在 OnStart 中启动后台工作程序而不是构造函数,并在 OnStop 中停止它。

您还可以检查事件日志中的异常情况,and/or 添加日志记录以了解是否从服务中抛出异常。