Bước 1 - Tạo mới Windows Service Application.
Bước 2 - Để chạy Windows Service, bạn cần cài đặt Installer, đăng ký nó với Service Control Manager. Click chuột phải vào Service1.cs[Design] và chọn Add Installer.
Bước 3 - Click chuột phải vào ProjectInstaller.cs [Design] và chọn View Code.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;
namespace DemoWindowsService {
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer {
public ProjectInstaller() {
InitializeComponent();
}
}
}
Nhấn F12 để đi đến implementation của InitializeComponent class. Thêm service name và description sẽ là tên windows service khi cài đặt.
private void InitializeComponent() {
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
// serviceProcessInstaller1
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
// serviceInstaller1
this.serviceInstaller1.Description = "My Demo Service";
this.serviceInstaller1.ServiceName = "DemoService";
// ProjectInstaller
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1
});
}
Bước 4 - Thêm logic ghi log vào file text trong class Service1.cs.
using System;
using System.IO;
using System.ServiceProcess;
using System.Timers;
namespace DemoWindowsService {
public partial class Service1 : ServiceBase {
Timer timer = new Timer();
public Service1() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
WriteToFile("Service started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000;
timer.Enabled = true;
}
protected override void OnStop() {
WriteToFile("Service stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e) {
WriteToFile("Service recall at " + DateTime.Now);
}
public void WriteToFile(string Message) {
string path = @"D:\Demo";
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
string filepath = @"D:\Demo\Log.txt";
if (!File.Exists(filepath)) {
using (StreamWriter sw = File.CreateText(filepath)) {
sw.WriteLine(Message);
}
} else {
using (StreamWriter sw = File.AppendText(filepath)) {
sw.WriteLine(Message);
}
}
}
}
}
Bước 5 (Cài đặt) - Cài đặt windows service dùng command prompt. Mở command prompt as administrator và chạy lệnh:
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Mở folder chứa file exe của windows service và chạy:
InstallUtil.exe C:\Users\[UserName]\source\repos\DemoWindowsService\DemoWindowsService\bin\Debug\DemoWindowsService.exe
Mở Services từ Windows application menu. Ta thấy windows service đã được cài đặt và chạy như mong đợi.
Các lệnh hữu ích khác
Gỡ cài đặt service
InstallUtil.exe /u C:\Path\To\YourService.exe
Khởi động service
net start DemoService
Dừng service
net stop DemoService
Xem trạng thái service
sc query DemoService
Cách hiện đại: .NET Core / .NET 5+ Generic Host
Từ .NET Core, Windows Service được xây dựng bằng Generic Host và Microsoft.Extensions.Hosting.WindowsServices:
// Program.cs
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
public class Program {
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService() // Quan trọng: cho phép chạy as Windows Service
.ConfigureServices((hostContext, services) => {
services.AddHostedService();
});
}
// Worker.cs
public class Worker : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
// Logic ở đây
await Task.Delay(5000, stoppingToken);
}
}
}
Cài đặt .NET Core Windows Service
# Publish dotnet publish -c Release -r win-x64 --self-contained true # Cài đặt (PowerShell as Admin) New-Service -Name "MyDotNetService" -BinaryPathName "C:\Path\MyService.exe" -DisplayName "My .NET Service" -StartupType Automatic # Hoặc dùng sc.exe sc.exe create "MyDotNetService" binPath= "C:\Path\MyService.exe" start= auto