MSDN Documentation

Microsoft Developer Network

Creating a Windows Service

This article guides you through the process of creating, installing, and managing a Windows Service using modern .NET technologies.

1. Introduction

Windows Services are long-running applications that run in the background, without a user interface, and can be configured to start automatically when the system boots up. They are essential for various system-level tasks, such as data processing, scheduled operations, and managing hardware. This guide focuses on creating services using C# and the .NET framework.

2. Prerequisites

3. Creating the Service Project

To begin, you need to create a new project in Visual Studio:

  1. Open Visual Studio.
  2. Click "Create a new project".
  3. Search for "Worker Service". Select the C# template.
  4. Click "Next".
  5. Name your project (e.g., "MyAwesomeService").
  6. Choose a location and click "Create".

The project template provides a basic structure for a Windows Service. The `Worker.cs` file contains the main logic for your service.

4. Implementing Service Logic

The core of your Windows Service logic resides within the `ExecuteAsync` method in your `Worker.cs` file. This method is called when the service starts and is executed repeatedly based on your defined intervals or conditions.

Important: The `ExecuteAsync` method should not block. Use asynchronous operations where possible.

Here's a simple example that logs a message every 10 seconds:

using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace MyAwesomeService { public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); // Replace this with your actual service logic await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); } } } }

Dependency Injection

The Worker Service template is built with dependency injection in mind. You can inject services like `ILogger`, `IConfiguration`, or custom services into your `Worker` class constructor.

Configuration

You can leverage `appsettings.json` for configuration. The template includes basic configuration setup. You can add custom settings for intervals, file paths, etc.

5. Installing the Service

To install your application as a Windows Service, you need to publish it and then use the `sc.exe` command-line utility or a service installer.

Publishing the Application

Right-click on your project in Solution Explorer and select "Publish". Choose "Folder" as the target and select a deployment path. Ensure you select the correct framework and runtime (e.g., `win-x64` for 64-bit Windows).

Using `sc.exe`

  1. Open Command Prompt as Administrator.
  2. Navigate to your publish directory.
  3. Run the following command to install the service:
sc create MyAwesomeService binPath= "C:\Path\To\Your\Publish\Folder\MyAwesomeService.exe" DisplayName= "My Awesome Service" start= auto

Replace `MyAwesomeService`, the path, and `DisplayName` with your actual service name and path.

Note: For more complex installation scenarios, consider using installers like WiX Toolset or InstallShield.

6. Managing the Service

You can manage your Windows Service through the Services administrative tool or via the command line.

Using the Services Tool

  1. Press `Win + R`, type `services.msc`, and press Enter.
  2. Find your service (e.g., "My Awesome Service") in the list.
  3. Right-click to Start, Stop, Restart, or change its Startup type.

Using `sc.exe` (as Administrator)

By following these steps, you can effectively create, deploy, and manage Windows Services for your background processing needs.