Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
| Scenario/Problem: | You want to put your code in a service so that it is more easily manageable and can run when users are not logged in.
There is nothing inherently different about a Windows service compared to an application except the manageability interfaces it implements (to allow it to be remotely controlled, automatically started and stopped, failed over to different machines, and so on). Also, a Windows service has no user interface (and security settings generally prohibit services from attempting to invoke a UI). You can generally use all the same .NET code as in a regular application. |
| Solution: | The heart of a service is a class that implements System.ServiceProcess.ServiceBase:
Code View:
Scroll
/
Show All public partial class GenericService : ServiceBase
{
Thread _programThread;
bool _continueRunning = false;
public GenericService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_continueRunning = true;
LogString("Service starting");
_programThread = new Thread(new ThreadStart(ThreadProc));
_programThread.Start();
}
protected override void OnStop()
{
_continueRunning = false;
LogString("Service stopping");
}
private void LogString(string line)
{
using (FileStream fs = new FileStream(
@"C:\GenericService_Output.log", FileMode.Append))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine(line);
}
}
private void ThreadProc()
{
while (_continueRunning)
{
Thread.Sleep(5000);
LogString(string.Format("{0} - Service running.",
DateTime.Now));
}
}
}
|
This service does nothing interesting—it just logs events to a file.