Timer and Window Service in C#

Step 1. Create Skeleton of the Service

To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.

The result look like this. The Wizard adds WebService1.cs class to your project.

Set your ServiceName to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line this.ServiceName = “mcWinService”;

This is the name you will be looking for later🙂.

The default code of WebService1.cs added by the Wizard looks like here

namespace mcWebService
{
using
System;
using
System.Collections;
using
System.Core;
using
System.ComponentModel;
using
System.Configuration;
using
System.Data;
using
System.Web.Services;
using
System.Diagnostics;
using
System.ServiceProcess;
public class
WinService1 : System.ServiceProcess.ServiceBase
{
/// <summary>

///
Required designer variable.
/// </summary>

private
System.ComponentModel.Container components;
public
WinService1()
{
// This call is required by the WinForms Component Designer. InitializeComponent();

// TODO: Add any initialization after the InitComponent call
}
// The main entry point for the process
static void
Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
/ create a second service object. For example,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new WinService1(), new
ySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary>

///
Required method for Designer support – do not modify
///
the contents of this method with the code editor.
/// </summary>

private void
InitializeComponent()
{
components =
new
System.ComponentModel.Container();
this
.ServiceName = “WinService1”;
}
/// <summary>

///
Set things in motion so your service can do its work.
/// </summary>

protected override void OnStart(string
[] args)
{
// TODO: Add code here to start your service.
}
/// <summary>

///
Stop this service.
/// </summary>

protected override void
OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}

Step 2. Add functionality to your service

As you saw WebService1.cs, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service.

private static System.Threading.Timer serviceTimer;

protected override void OnStart(string[] args)
{
FileStream fs =
new
FileStream(@”c:\temp\mcWindowsService.txt” ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new
StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(” mcWindowsService: Service Started \n”);
m_streamWriter.Flush();
m_streamWriter.Close();

TimerCallback timerDelegate =   new TimerCallback(DoWork);

// create timer and attach our method delegate to it
serviceTimer =
new Timer(timerDelegate, null, 1000,10000); //(x,y,delay before start, interval between invocations of callbacks)

}
/// <summary>

///
Stop this service.
/// </summary>

protected override void
OnStop()
{
FileStream fs =
new
FileStream(@”c:\temp\mcWindowsService.txt” ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new
StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(” mcWindowsService: Service Stopped \n”); m_streamWriter.Flush();
m_streamWriter.Close();
}

private void DoWork(object state)
{
FileStream fs = new FileStream(@”c:\temp\mcWindowsService.txt”,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(string.Format(” Doing work: {0} \n”,DateTime.Now.ToString())); m_streamWriter.Flush();
m_streamWriter.Close();

}

After Step 2.

Please follow the below mentioned step before jumping to Step 3.
Step 2.5 :

a) Return to Design view for WinService1.

b)Click the background of the designer to select the service itself, rather than any of its contents.

c)Rigth click on the Designed Windows and in the Properties window, click the Add Installer link in the gray area beneath the list of properties.

d)By default, a component class containing two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service’s associated process.

e)Access Design view for ProjectInstaller, and click ServiceInstaller1. In the Properties window, set the ServiceName property to MyNewService. Set the StartType property to Automatic.

f)In the designer, select ServiceProcessInstaller1 (for a Visual Basic project), or serviceProcessInstaller1 (for a Visual C# project). Set the Account property to LocalService. This will cause the service to be installed and to run on a local service account.

After the above procedure, try re-registering using InstallUtil utilities.

g) Create folder: C:/temp

Step 3: Install and Run the Service

Open Visual Studio 2008 Command Line with administrator right.

Install: installutil /i C:\Banana\References\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe

Uninstall: installutil /u C:\Banana\References\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe

Sometimes, it is quite difficult to remove a service (if the service is error by installer). The uninstalled way can be solve by manual.

  • Open Start, Run, type: regedit, enter
  • HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services
  • Delete suitable service .
  • Restart

Step 4: Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.

Under Services and Applications, you will see the service mcWinService. Start and Stop menu item starts and stops the service.

Step 5: Test the Service

Go to your temp directory and see if text file is there with contents or not.
Reference: http://www.c-sharpcorner.com/UploadFile/mahesh/window_service11262005045007AM/window_service.aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: