Hello,
I am by far not a C-Sharp guru but I have found a simple way to
start/stop a service. I start a new thread to do the Service process
in the OnStart() function and on OnStop() I try to make the Run() loop
exit gracefully. If it is still running after a specified time, I kill
the Thread with Thread.Abort() You may find a little more graceful way
than this, but so far, I haven't had a problem. I would guess you
have to start a new thread or procecss in the OnStart() since you
can't put your main process in the OnStart() Entrypoint. You have to
return from the OnStart function relatively quickly or the Service
Control Manager will complain. I cannot say whether Thread.Abort()
will do all of the necessary freeing/disposing of resources that you
might like. You may need to use private member variables to keep track
of Forms (not recommended in services) or other resources that you
want to make sure are disposed of properly.
Anyway, here is the sample code... A sample is worth a million words
when you are new to a language--And boy do I appreciate all of the
great examples found here in the Google Forums. I hope this is of some
help to you. If not, good luck in your search for your answers.
Scott Numbers
numbers @ adelphia.net
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace WindowsService1
{
public class Service1 : System.ServiceProcess.ServiceBase
{
private System.ComponentModel.Container components = null;
private System.Threading.Thread ServiceThread =
(System.Threading.Thread) null;
private bool mRunning = false;
public Service1()
{
InitializeComponent();
}
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
private void Run()
{
// Do your service Loop/Listener/Whatever
// Possible loop
while (mRunning) {
Thread.Sleep(5000); // Sleep 5 seconds
if (xyz) {
DoSomething();
}
}
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
protected override void OnStart(string[] args)
{
mRunning = true;
System.Threading.ThreadStart ts =
new System.Threading.ThreadStart(Run);
ServiceThread = new System.Threading.Thread(ts);
ServiceThread.Start();
}
protected override void OnStop()
{
mRunning = false;
// Time should be longer than Run() loop takes to execute.
Thread.Sleep(8000);
// If the thread hasn't exited on its own by now,
// Kill it.
if (ServiceThread.IsAlive) ServiceThread.Abort();
// I'm lost if I can't say "Set xyz = Nothing"
ServiceThread = (System.Threading.Thread) null;
}
}
}