sodcalculator

10 Tech How-To

How to Create a Windows Service (Step-by-Step)

Guide 10-30551 · Updated · Step by step

This guide walks you through creating a Windows service from scratch, using C# and the .NET Framework or .NET Core. You’ll learn the essential steps, from setting up the project to installing and debugging your service, so you can run background tasks automatically on Windows.

What You’ll Need

  • Windows 10 or 11 (or Windows Server 2016+)
  • Visual Studio 2022 (Community edition is free) or the .NET SDK
  • Administrator access to install the service
  • Basic familiarity with C# and command line

Step-by-Step

  1. Create a new project. Open Visual Studio, select Create a new project, choose Worker Service (for .NET Core) or Windows Service (for .NET Framework). Name it, e.g., MyService.
  2. Add the necessary NuGet package. For .NET Core, right-click your project, select Manage NuGet Packages, and install Microsoft.Extensions.Hosting.WindowsServices. This package provides the Windows-specific service integration.
  3. Modify the Program.cs file. In .NET Core, change the CreateHostBuilder method to call UseWindowsService(). Example:
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });

    For .NET Framework, the template already generates a ServiceBase subclass.

  4. Implement the service logic. In the Worker class (or the service class), override the ExecuteAsync method (or OnStart and OnStop for .NET Framework) to define what your service does. For example, write to a log file every minute.
  5. Set the service name and description. In the Worker class, add the [ServiceName] attribute or set it in the project properties. For .NET Core, you can set the service name in the UseWindowsService options:
    .UseWindowsService(options => options.ServiceName = "MyService")

    Also, add a Description attribute to the class for a friendly description in the Services console.

  6. Build the project. Press Ctrl+Shift+B to compile. Ensure the output folder contains the executable (e.g., MyService.exe).
  7. Install the service. Open a command prompt as Administrator. Navigate to the output folder (e.g., bin\Debug\net8.0) and run:
    sc create MyService binPath= "C:\path\to\MyService.exe" start= auto

    Or use the installutil.exe tool for .NET Framework services:

    installutil MyService.exe

    For .NET Core, you can also use sc.exe or create an installer with the Microsoft.Extensions.Hosting.WindowsServices package.

  8. Start the service. Run sc start MyService or open the Services app (services.msc), find your service, and click Start.
  9. Verify it works. Check the log file or event viewer to confirm your service is running. You can also use sc query MyService to see the status.
  10. Stop and uninstall (if needed). Use sc stop MyService and sc delete MyService to stop and remove the service.

Common Mistakes

  • Forgetting to call UseWindowsService(). Without this, the service won’t run as a Windows service; it will run as a console app.
  • Running the executable directly. A service must be installed and started by the Service Control Manager; double-clicking the .exe won’t work as expected.
  • Not running the install command as Administrator. You’ll get an access denied error.
  • Using the wrong path in sc create. The binPath must be the full absolute path to the executable, and it may need quotes if the path contains spaces.
  • Not handling exceptions in the service logic. If an unhandled exception occurs, the service will crash and stop.

Tips

  • Use a try-catch in your service’s main loop to log errors and keep the service running.
  • Set the StartType to Automatic if you want the service to start on boot. You can do this in the sc create command or via the Services app.
  • For debugging, run the service as a console app. In Visual Studio, change the output type to Console Application temporarily, or add a condition to run as console if a command-line argument like --console is passed.
  • Use the Event Viewer to log service events. Write to the Windows event log using EventLog class for easier troubleshooting.
  • Test on a virtual machine first. This avoids messing up your main system if the service misbehaves.

Troubleshooting

  • Service fails to start with error 1053. This means the service didn’t respond to the start request in time. Check your OnStart method for blocking operations. Move long-running tasks to a separate thread or use ExecuteAsync properly.
  • Error 193: %1 is not a valid Win32 application. This usually means you’re trying to run a .NET Core service without the correct runtime installed, or the path points to a DLL instead of the EXE. Ensure the .NET runtime is installed and the binPath points to the executable.
  • Access denied when installing. Make sure you are running the command prompt as Administrator.
  • Service shows as “Start Pending” and then stops. Check the Event Viewer for application errors. The service may be throwing an unhandled exception during start.
  • Changes to the code don’t take effect. You must rebuild the project and then stop, uninstall, reinstall, and start the service again. Simply copying a new .exe over the old one while the service is running won’t work.
  • Can’t find the service in the Services app. Make sure you used the correct service name and that the installation succeeded. Run sc query to list all services and grep for your name.

Frequently Asked Questions

Can I create a Windows service without Visual Studio?

Yes, you can use the .NET SDK with a text editor and the command line. The process is the same, but you’ll need to manually create the project files and build using dotnet build.

What’s the difference between a Windows service and a regular app?

A Windows service runs in the background without a user interface, starts automatically at boot (if configured), and is managed by the Service Control Manager. A regular app requires a user to log in and run it.

Can I run a Python script as a Windows service?

Yes, you can wrap a Python script in a Windows service using tools like NSSM (Non-Sucking Service Manager) or by creating a small C# wrapper that launches the Python process.

How do I debug a Windows service?

You can attach the Visual Studio debugger to the running service process, or run the service as a console app with a special argument (e.g., --console) to debug it like a normal program.

Is it possible to create a service that runs a scheduled task?

Yes, you can implement a timer inside your service to execute code at specific intervals. Alternatively, use the Windows Task Scheduler, which is often simpler for scheduled tasks.

Do I need to install .NET on the target machine?

Yes, if you use .NET Core, the target machine must have the .NET runtime installed. You can publish a self-contained deployment that includes the runtime, but that increases the size.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →