Windows service for continuous operation

Ive created a Windows service called ProxyMonitor and im is currently in the process of installing and uninstalling the service as I want it.

So, I am running the application as follows:

C:\\Windows\\Vendor\\ProxyMonitor.exe /install 

Pretty explanatory, and then I got to services.msc and started the service, but when I do this, I get the following message:

The proxy monitor service on the local computer started and then stopped. Some services automatically stop if there is no work, such as Performance Logs and Alerts

My code looks like this:

 public static Main(string[] Args) { if (System.Environment.UserInteractive) { /* * Here I have my install logic */ } else { ServiceBase.Run(new ProxyMonitor()); } } 

And then in the ProxyMonitor class I have:

 public ProxyMonitor() { } protected override void OnStart(string[] args) { base.OnStart(args); ProxyEventLog.WriteEntry("ProxyMonitor Started"); running = true; while (running) { //Execution Loop } } 

and onStop() I just change the running variable to false ;

What do I need to do to make the service constantly active, since I will need to control the network on which I need to track changes, etc.




Update: 1

 protected override void OnStart(string[] args) { base.OnStart(args); ProxyEventLog.WriteEntry("ProxyMonitor Started"); Thread = new Thread(ThreadWorker); Thread.Start(); } 

In ThreadWorker , I have a ProxyEventLogger.WriteEntry("Main thread entered") that does not work.

+44
c # windows-services
Feb 01 '11 at 15:47
source share
5 answers

The OnStart() callback should return in a timely manner, so you want to start a thread where all your work will be done. I would recommend adding the following fields to the class:

 using System.Threading; private ManualResetEvent _shutdownEvent = new ManualResetEvent(false); private Thread _thread; 

The _thread field will contain a reference to the System.Threading.Thread object that you create in the OnStart() callback. The _shutdownEvent field contains a system-level event construct that will be used to signal that the thread has stopped working when the service _shutdownEvent .

In the OnStart() callback, create and start your thread.

 protected override void OnStart(string[] args) { _thread = new Thread(WorkerThreadFunc); _thread.Name = "My Worker Thread"; _thread.IsBackground = true; _thread.Start(); } 

To do this, you need a function called WorkerThreadFunc . It must match the System.Threading.ThreadStart subscription.

 private void WorkerThreadFunc() { } 

If you don’t put anything into this function, the thread will start and then shut down right away, so you have to put some logic in there that basically saves the stream while you are doing your work. Here _shutdownEvent in handy.

 private void WorkerThreadFunc() { while (!_shutdownEvent.WaitOne(0)) { // Replace the Sleep() call with the work you need to do Thread.Sleep(1000); } } 

The while loop checks ManualResetEvent to make sure it is set or not. Since we initialized the object with false above, this check returns false. Inside the cycle, we sleep for 1 second. You will want to replace this with the work that you must do - control the proxy server settings, etc.

Finally, in the OnStop() your Windows Service, you want the thread to stop working. This is easy to use with _shutdownEvent .

 protected override void OnStop() { _shutdownEvent.Set(); if (!_thread.Join(3000)) { // give the thread 3 seconds to stop _thread.Abort(); } } 

Hope this helps.

+112
Feb 01 '11 at 17:31
source share

You need to exit the OnStart handler so that the service manager understands that your service has really started. To make it work the way you want, you can start a timer that ticks at intervals and processes when it ticks.

Edit:

Try typing System.Diagnostics.Debugger.Launch () in your OnStart to see what happens (and put a breakpoint in ThreadWorker ). I would recommend wrapping this in #if DEBUG to make sure it doesn't deploy.

I just realized that you would not give your Thread name:

  Thread myThread = new Thread(ThreadWorker); myThread.Start(); 
+6
Feb 01 '11 at 15:50
source share

Of course, not adding a while to the OnStart method. This will tell the OS that the service is not running because it could not safely exit the OnStart method. Usually I create a Timer that is included in the OnStart method. Then, in the Ticks method, I call the necessary method to make the application work.

Alternatively, you can do the following:

 // The main entry point for the process static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } 

For more information about Windows services, you can get an example skeleton here .

+2
Feb 01 '11 at 15:56
source share

Sample code demonstrated using a console application. hope this helps ..

  class Program { private static CancellationTokenSource _cancellationTokenSource; private static ManualResetEvent _shutdownEvent = new ManualResetEvent(false); private static Thread _serviceStartThread; private static Thread _serviceStopThread; private static int workcounter = 0; static void Main(string[] args) { _cancellationTokenSource = new CancellationTokenSource(); _serviceStartThread = new Thread(DoWork); _serviceStopThread = new Thread(ScheduledStop); StartService(); StopService(); } private static void StartService() { _serviceStartThread.Start(); } private static void StopService() { _serviceStopThread.Start(); } /// <summary> /// Triggers a cancellation event for stopping the service in a timely fashion. /// </summary> private static void ScheduledStop() { while (!_shutdownEvent.WaitOne(0)) { if (workcounter == 10) { _cancellationTokenSource.Cancel(); } } } /// <summary> /// Represents a long running Task with cancellation option /// </summary> private static void DoWork() { while (!_shutdownEvent.WaitOne(0)) { if(!_cancellationTokenSource.Token.IsCancellationRequested) { workcounter += 1; Console.Write(Environment.NewLine); Console.Write("Running...counter: " + workcounter.ToString()); Thread.Sleep(1000);//Not needed, just for demo.. } else { Console.Write(Environment.NewLine); Console.Write("Recieved cancellation token,shutting down in 5 seconds.. counter: " + workcounter.ToString()); _shutdownEvent.Set(); Thread.Sleep(5000);//Not needed, just for demo.. } } } } 
+1
Apr 7 '17 at 9:05
source share

Why don't you create a new project in your solution like Windows Service? This sets up all the structures that need to be implemented, including even handlers for service start / stop events.

0
Feb 01 '11 at 15:49
source share



All Articles