Creating a Windows Service with C#, continued - Coding the Service
(Page 3 of 4 )
Now we need to do something about our control loop, since we can’t use console input anymore to kill the program. We also need to decide what type of event logging we are going to do.
To control our loop, we need to add a property to the class; we will call it “isStopped.” We will have to add a couple of lines to the OnStart() and OnStop() methods. Add this to the properties section of the class:
private bool isStopped = false;
The new OnStart(), OnStop(), and Start() methods are shown below:
protected override void OnStart(string[] args)
{
this.isStopped = false;
this.Start();
}
protected override void OnStop()
{
this.isStopped = true;
}
public void Start()
{
this.listener.Start();
Socket s;
Byte[] incomingBuffer;
Byte[] time;
int bytesRead;
while (!this.isStopped)
{
s = this.listener.AcceptSocket();
incomingBuffer = new Byte[100];
bytesRead = s.Receive(incomingBuffer);
time = Encoding.ASCII.GetBytes(
System.DateTime.Now.ToString().ToCharArray());
s.Send(time);
}
this.listener.Stop();
}
Now the server will start and stop using the built in Windows Service hooks.
Next: Installing the Service >>
More C# Articles
More By David Fells