Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

Create a Windows Service

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:
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.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial