简体   繁体   中英

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

I am implementing a Windows Service in C #, Visual Studio 2010 IDE.

I tried first to make a small application with a timer writing to a file every 5 seconds and works perfectly. Good service and everything starts.

After this test, what I need is to make a service that writes to a file "USB memory is entered" and "remove USB memory". I keep track of how many times I enter a memory.

This is my code.

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);
        }
    }
}

The fact is that when the service reaches the task manager / services, is always stopped, doi you right click and starts, and remains stopped.

If the timer worked well and I only started because this code does not? I can have that problem? any ideas?regards

Check the documentation for 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.

So it sounds like you need to start your background worker in OnStart instead of the constructor, and stop it in OnStop .

You might also check the event log for exceptions, and/or add logging to know if an exception is thrown from within the service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM