Windows Services are background applications that run without UI and start automatically with Windows. They are ideal for:
✔ Scheduled tasks
✔ File monitoring
✔ Background processing
✔ Automation jobs
✔ Queue listeners
Step 1: Create the Windows Service Project
In Visual Studio
Open Visual Studio
Click Create a new project
Search for Windows Service (.NET Framework)
(Use .NET Framework version 4.7.2+)
Give it a name → e.g., MyWindowsService
Click Create
You will see a class called:
public partial class Service1 : ServiceBase
Step 2: Write Service Code
Open Service1.cs → write logic inside OnStart and OnStop.
public partial class Service1 : ServiceBase
{
private System.Timers.Timer timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Interval = 5000; // runs every 5 seconds
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
WriteLog("Service is running at: " + DateTime.Now);
}
protected override void OnStop()
{
WriteLog("Service stopped.");
}
private void WriteLog(string message)
{
string path = @"C:\MyServiceLog.txt";
File.AppendAllText(path, message + Environment.NewLine);
}
}
Step 3: Add Installer (Required!)
Right-click inside Service1.cs → Add Installer
It will generate two components:
✔ ServiceProcessInstaller
✔ ServiceInstaller
Set properties
ServiceProcessInstaller
Account = System.ServiceProcess.ServiceAccount.LocalSystem;
ServiceInstaller
ServiceName = "MyWindowsService";
StartType = Automatic;
Step 4: Build the Project
Go to:
Build → Build Solution
It creates .exe inside:
bin\Release\
Step 5: Install the Service (Windows CMD)
Open Command Prompt as Administrator.
Run:
sc create MyWindowsService binPath= "C:\Path\To\MyWindowsService.exe"
Start the service:
sc start MyWindowsService
Stop the service:
sc stop MyWindowsService
Delete service:
sc delete MyWindowsService
Alternative Installation (PowerShell)
New-Service -Name "MyWindowsService" -BinaryPathName "C:\Path\MyWindowsService.exe"
Start-Service MyWindowsService
Step 6: Debugging Windows Service
Windows services cannot run by double-click.
To debug:
Option 1 — Temporary Console Mode
Add this code:
#if DEBUG
System.Threading.Thread.Sleep(10000);
#endif
Or create a console runner.
Option 2 — Attach to Process
Install service
Start service
In Visual Studio → Debug → Attach to Process
Select your service EXE
Add breakpoints → Debug
Top Use Cases
| Use Case | Why Windows Service? |
|---|
| Auto-backup jobs | Runs even when user is logged out |
| File monitoring | Continuous background watch |
| Sending emails | No UI required |
| Data sync jobs | Runs at startup |
| Long-running jobs | Stable background processing |