C # — Overview of Windows Services (WS)

This article will give you an overview of Windows Service, as well as how to write a Windows Services to handle tasks running in the background.

Image for post
Image for post
Photo by Andrew Mantarro on Unsplash

What is Windows Services?

  • Windows Service can be roughly understood as a background application for a long time from when you turn on the computer until it is turned off.
  • It can run automatically when the computer is booted up, can be restarted or paused without any user intervention on UI-related tools.
  • Can be installed easily thanks to Visual Studio exe’s built-in support tool via Command-Line. You just need to point the available directory of the exe file and execute it. So you’ve installed Windows Service.

Why use WS?

  • One of the most important customer requests is: have an application running in the background every day to aggregate data used to generate reports, synchronize data from servers, see how many products have been sold today, or is sending an email to users when their account has expired, v … v … 😀
  • Building a WS can be considered as an optimal solution for the above situations without the user having to manipulate WS at all, everything is run in the background on their computer/server.

Write a simple Window Services

With the above issues, this article I will guide you to build a WS from basic to advanced step by step 1 (this is what I learned from the actual project so I want to share with you. : D).

First, we will create a Windows Service Project as follows.

Image for post
Image for post
Image for post
Image for post

After creating the project, next, we will create a Utilities class to write to the log file of WS events as follows.

public class Utilities
{
public static void WriteLogError (Exception ex)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter (AppDomain.CurrentDomain.BaseDirectory + "\\ LogFile.txt", true);
sw.WriteLine (DateTime.Now.ToString ("g") + ":" + ex.Source + ";" + ex.Message);
sw.Flush ();
sw.Close ();
}
catch
{
// ignored
}
}
public static void WriteLogError (string message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter (AppDomain.CurrentDomain.BaseDirectory + "\\ LogFile.txt", true);
sw.WriteLine (DateTime.Now.ToString ("g") + ":" + message);
sw.Flush ();
sw.Close ();
}
catch
{
// ignored
}
}
}

Next, we will return to the Service1.cs class to start implementing the main part of the Service. In this introductory article, I will do the basic steps first for you to visualize the flow of Windows Service first.

public class Service1
{
private Timer timer = null;
public Service1 ()
{
InitializeComponent ();
}

protected override void OnStart (string [] args)
{
// Create a timer from libary System.Timers
timer = new Timer ();
// Execute every 60s
timer.Interval = 60000;
// What happens when that timer is ticked
timer.Elapsed + = timer_Tick;
// Enable timer
timer.Enabled = true;
// Write log file when services dc start for the first time
Utilities.WriteLogError ("Test for 1st run WindowsService");
}

private void timer_Tick (object sender, ElapsedEventArgs args)
{
// Handle some logic here
Utilities.WriteLogError ("Timer has ticked for doing something !!!");
}

protected override void OnStop ()
{
// Log when the Services have been stopped
timer.Enabled = true;
Utilities.WriteLogError ("1st WindowsService has been stopped");
}
}

Coming here is quite simple to understand right, we will call the timer_Tick function every 60s to make a business something. Next, we return to Service1.cs UI design and right-click on it to create an Installer for our WS.

Image for post
Image for post

After creating 1 Installer, we will go to properties to configure the necessary things such as ServicesName and StartType. In this example, I will select the mode Manual for a demo, you can use automatically or disabled.

Image for post
Image for post
Image for post
Image for post

Then we will adjust the parameters for Process Installer as follows. Because for the demo, I will use the local machine to execute, so I will choose Account is LocalSystem.

Image for post
Image for post
Image for post
Image for post

You have already written 1 Windows Service already. Build the project and read the following to know how to install Windows Service.

Install Windows Service

Open the Command line of Visual Studio 2015 as follows: Start -> All Programs -> Visual Studio 2015 -> Visual Studio Tools -> Developer Command Prompt for VS2015. Go to the debug directory of Project Windows Service.

Image for post
Image for post

Here we will use the Install command, behind the Install is the name of the exe file containing the Service:

InstallUtil “FirstWindowsService.exe”
Image for post
Image for post
Image for post
Image for post

If you see the results, as shown above, you have successfully installed it. The final step is to start the Services and look at the log file.

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

At this point, you probably understand how to build a WS.

Written by

Always be nice to anybody who has access to my toothbrush.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store