TechBuzzPro

Create a Windows Service with .NET Core: Step-by-Step

· 7 min read · Windows & PC

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can create a Windows Service with .NET Core (now called .NET) by making a Worker Service project, adding the Windows Service package, calling UseWindowsService in the host builder, and then publishing and registering the executable with sc.exe. The Worker Service template gives you a background loop that runs on a timer; the Windows Service integration makes that loop start automatically at boot and run without a logged-in user. This guide uses the .NET CLI and the Windows Service Control Manager, which are the official tools for this job.

What You'll Need

  • Windows 10, Windows 11, or Windows Server with administrator rights (you need admin to install a service).
  • The .NET SDK installed. Check with dotnet --list-sdks in a terminal. If it prints nothing, install the SDK from Microsoft's official download page.
  • A terminal: Command Prompt, PowerShell, or Windows Terminal. PowerShell is fine; run it as Administrator when you install the service.
  • Basic familiarity with C# and editing a project file.

Step-by-Step

  1. Create the Worker Service project. Open a terminal in the folder where you keep code and run:

    dotnet new worker -n MyWorkerService

    Then move into it: cd MyWorkerService. The template creates Program.cs, Worker.cs, and a project file. Menu and command names in the .NET CLI are stable, but template contents can differ slightly between SDK versions, so read the generated files rather than assuming.

  2. Add the Windows Service package. Run:

    dotnet add package Microsoft.Extensions.Hosting.WindowsServices

    This package provides the UseWindowsService extension method that wires the generic host into the Windows Service Control Manager. Without it, the executable will start and immediately exit when the Service Control Manager launches it.

  3. Enable Windows Service support in the host. Open Program.cs. The template builds a host with Host.CreateApplicationBuilder(args) (newer SDKs) or Host.CreateDefaultBuilder(args) (older SDKs). Add the call like this for the builder style:

    var builder = Host.CreateApplicationBuilder(args);
    builder.Services.AddWindowsService(options => { options.ServiceName = "MyWorkerService"; });
    builder.Services.AddHostedService<Worker>();
    var host = builder.Build();
    host.Run();

    For the older builder style, chain it: Host.CreateDefaultBuilder(args).UseWindowsService(options => { options.ServiceName = "MyWorkerService"; });. Setting ServiceName makes the Windows Event Log entries use your service name instead of the generic application name.

  4. Write the work your service should do. Open Worker.cs. The template has an ExecuteAsync method that loops until cancellation. Put your real logic inside that loop, and always respect the stoppingToken so the service shuts down cleanly when Windows stops it. A common pattern is while (!stoppingToken.IsCancellationRequested) { /* do work */ await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); }. Catch exceptions inside the loop so one failure does not kill the whole service; log them instead.

  5. Build and test as a console app first. Run dotnet run. The same code runs as a normal console program when it is not started by the Service Control Manager, which makes debugging far easier. Confirm your loop works and your logging appears before you install anything.

  6. Publish a self-contained or framework-dependent build. From the project folder run:

    dotnet publish -c Release -r win-x64 --self-contained false -o C:\Services\MyWorkerService

    Use --self-contained true if the target machine will not have the matching .NET runtime installed; the output folder will be larger but needs nothing else. The -o path is where the executable lands. Note that win-x64 is for 64-bit Windows; use win-arm64 only on ARM devices.

  7. Install the service. Open PowerShell or Command Prompt as Administrator and run:

    sc.exe create MyWorkerService binPath= "C:\Services\MyWorkerService\MyWorkerService.exe" start= auto

    The spaces after binPath= and start= are required by sc.exe; leaving them out is the single most common reason the command fails. Then start it: sc.exe start MyWorkerService. Check status with sc.exe query MyWorkerService.

  8. Verify it is running and logging. Open services.msc and confirm the service shows as Running with Startup type Automatic. If you use the default logging, check Windows Event Viewer under Windows Logs > Application for entries from your service name. Stop it with sc.exe stop MyWorkerService while testing.

  9. Remove the service when you no longer need it. Stop it first, then run sc.exe delete MyWorkerService as Administrator. Deleting the service does not delete your published files; remove the folder yourself if you want it gone.

Common Mistakes

  • Forgetting UseWindowsService. The service installs and starts, then exits with an error because the host does not know it is running as a service. The package and the call are both required.
  • Missing spaces in sc.exe arguments. binPath= needs a space before the quoted path. binPath="..." without the space is parsed incorrectly.
  • Using a relative path in binPath. Always give the full path to the published .exe. The service's working directory is not your project folder.
  • Assuming the service can show a UI. Windows services run in a non-interactive session. Any console output, message box, or user prompt will not appear. Log to a file or the Event Log instead.
  • Ignoring the cancellation token. A loop that never checks stoppingToken makes the service hang on stop and eventually get killed by Windows.
  • Publishing framework-dependent to a machine without the runtime. The service fails to start with a missing runtime error. Publish self-contained or install the correct runtime first.
  • Running as the wrong account. By default the service runs as LocalSystem. If your code touches network shares or user-specific files, that identity may not have access; set an account in the service's properties in services.msc if needed.

Tips

  • Keep the service name, the ServiceName option, and the executable name consistent so logs and Service Control Manager entries match.
  • Write logs to a file or the Event Log with a real logging provider; console output is discarded when running as a service.
  • Do long startup work in StartAsync and long-running work in ExecuteAsync so Windows does not time out the start request.
  • Set the service to restart on failure in services.msc under the Recovery tab, so a crash recovers without manual intervention.
  • Test the published executable by running it from a terminal before installing; if it crashes there, it will crash as a service too.

Troubleshooting

The service installs but stops immediately. Check Event Viewer > Windows Logs > Application for the exception. The usual causes are a missing UseWindowsService call, a missing runtime, or an unhandled exception in startup code.

sc.exe create returns an error. Confirm you are running the terminal as Administrator and that the binPath points to an existing .exe. Error 1053 (the service did not respond in a timely fashion) usually means startup work is blocking; move it off the start path.

The service runs but does nothing. Your loop may be exiting immediately, or the work may be throwing and being swallowed. Add logging at the top of ExecuteAsync and inside the loop, then restart the service and read the log.

Access denied when reading files or network paths. Change the account the service runs under in services.msc > your service > Properties > Log On, or grant the LocalSystem account the required permissions.

You changed the code but the service behaves the same. Stop the service, republish to the same folder, then start it again. The running service uses the files on disk at start time, not your build output.

Frequently Asked Questions

Can I debug a Windows Service in Visual Studio?

Yes, but the simplest route is to run the project as a console app with dotnet run and debug that. Attaching a debugger to an installed service is possible but slower to set up.

Does this work on Linux?

The Worker Service template does, but UseWindowsService and sc.exe are Windows-only. On Linux you would use systemd instead.

Do I need a separate installer?

No. Publishing the files and running sc.exe create is enough. An installer is only worth it if you need to copy files, set permissions, and register the service in one step.

How do I change the service to start manually?

Run sc.exe config MyWorkerService start= demand as Administrator, or change Startup type in services.msc.

Where does the service write logs by default?

To the Windows Event Log under the Application log, using the service name you set. For files, add a file logging provider and point it at a folder the service account can write to.

Can the service interact with the desktop?

No. Windows services cannot show windows or prompts to the logged-in user. Use a separate desktop app or a tray application if you need a UI.