Running a Hosted Service in a Console Application
When using the Worker template to create applications that use hosted services, you get a console you can type into. This is the normal use case, but what if you wanted to do some background work in a console application? I’ll show you how to do that here.
First, create a standard console application using -
dotnet new console -n HostedServiceInConsoleAppAdd the Microsoft.Extensions.Hosting package to the project -
dotnet add package Microsoft.Extensions.HostingCreate a new class that inherits from BackgroundService -
1using Microsoft.Extensions.Hosting;
2
3public class Worker() : BackgroundService
4{
5 int loop = 0;
6 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
7 {
8 while (!stoppingToken.IsCancellationRequested)
9 {
10 Console.WriteLine($"Worker called {++loop} times. {DateTime.Now.ToString("T")}");
11 await Task.Delay(1000, stoppingToken);
12 }
13 }
14}Back in Program.cs replace what is there with -
1using Microsoft.Extensions.Hosting;
2using Microsoft.Extensions.DependencyInjection;
3
4var builder = Host.CreateApplicationBuilder(args);
5builder.Services.AddHostedService<Worker>();
6var host = builder.Build();
7host.RunAsync();
8
9Console.WriteLine("Press c to cancel...");
10
11while(true)
12{
13 var keyPressed = Console.ReadKey().Key;
14
15 if(keyPressed == ConsoleKey.C)
16 {
17 Console.WriteLine("\nCancelling...");
18 await host.StopAsync();
19 break;
20 }
21 else
22 {
23 Console.WriteLine($"\nYou pressed {keyPressed}...");
24 }
25}Lines 4-7 create the application builder, add the background service, build, and run the host.
Lines 11-25 keep the application running and responding to key presses. Pressing c will stop the host and shut the application down.
This is a simple example of how to run a hosted service in a console application. You can add more background services, and make the console application as complex as you need.