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 HostedServiceInConsoleApp

Add the Microsoft.Extensions.Hosting package to the project -

dotnet add package Microsoft.Extensions.Hosting

Create a new class that inherits from BackgroundService -

 1public class Worker() : BackgroundService
 3    int loop = 0;
 4    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 5    {
 6        while (!stoppingToken.IsCancellationRequested)
 7        {
 8            Console.WriteLine($"Worker called {++loop} times. {DateTime.Now.ToString("T")}");
 9            await Task.Delay(1000, stoppingToken);
10        }
11    }

Back in Program.cs replace what is there with -

 1using Microsoft.Extensions.Hosting;
 2using Microsoft.Extensions.DependencyInjection;
 4var builder = Host.CreateApplicationBuilder(args);
 6var host = builder.Build();
 9Console.WriteLine("Press c to cancel...");
13    var keyPressed = Console.ReadKey().Key;
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    }

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.

comments powered by Disqus