Most .NET background work is fixed when the app starts: you register a BackgroundService and it runs until shutdown. This project takes a different approach: a small .NET 8 console app that starts, reconfigures and stops any number of named background workers while it is running, from simple typed commands.
#1. What It Does
The app prints a prompt and accepts five commands:
START <id> <interval-ms> <config>starts a new worker that runs every interval milliseconds with its own config value.UPDATE <id> <interval-ms> <config>changes a running worker's interval and config without restarting it.STOP <id>cancels one worker.LISTshows every running worker and its current settings.EXITquits.
That makes the number and pace of workers data, not code, which suits per-tenant pollers, sync jobs you switch on and off, or scheduled tasks whose frequency changes at runtime.
#2. How the Code Is Organised
Three files, each with one job:
Service&Instances/
├── Program.cs console loop: reads and parses commands
├── Service.cs MyBackgroundService + ConfigData: one worker
└── ServiceManager.cs BackgroundServiceManager: owns all workers#3. The Worker: MyBackgroundService
Each worker carries its settings in a small ConfigData class: how often to run, and a custom value standing in for whatever real settings a job would need.
public class ConfigData
{
public int Interval { get; set; } = 5000; // Default interval in milliseconds
public string CustomValue { get; set; } = "DefaultConfig";
}The worker itself is an async loop. It does its work (here, a log line), then waits for the interval with Task.Delay, and repeats until its CancellationTokenSource is cancelled:
private CancellationTokenSource _cts;
private string _serviceId;
private ConfigData _config;
public MyBackgroundService(string serviceId, ConfigData config)
{
_serviceId = serviceId;
_config = config;
_cts = new CancellationTokenSource();
}
public async Task StartAsync()
{
Console.WriteLine($"Service {_serviceId} started. Interval: {_config.Interval} ms, Config: {_config.CustomValue}");
while (!_cts.Token.IsCancellationRequested)
{
Console.WriteLine($"Service {_serviceId} is running with config: {_config.CustomValue}");
await Task.Delay(_config.Interval, _cts.Token);
}
Console.WriteLine($"Service {_serviceId} stopped.");
}
public void Stop()
{
_cts.Cancel();
}
public void UpdateConfig(ConfigData newConfig)
{
_config = newConfig;
Console.WriteLine($"Service {_serviceId} updated: Interval={_config.Interval} ms, Config={_config.CustomValue}");
}- Cancellation instead of flags. The loop checks
_cts.Token.IsCancellationRequested, and the same token is passed toTask.Delay, soStop()also interrupts a worker that is in the middle of waiting. - Config is read on every pass.
UpdateConfigjust replaces_config. The loop reads_configeach time round, so the next pass picks up the new value and interval. - Async, not threads. While a worker waits it holds no thread, so hundreds of workers cost almost nothing when idle.
#4. The Manager: BackgroundServiceManager
The manager owns all workers in a ConcurrentDictionary keyed by id. Each entry stores the worker together with its current config, so LIST can report settings without asking every worker.
public class BackgroundServiceManager
{
private readonly ConcurrentDictionary<string, (MyBackgroundService, ConfigData)> _services;
public BackgroundServiceManager()
{
_services = new ConcurrentDictionary<string, (MyBackgroundService, ConfigData)>();
}
public string StartService(string serviceId, ConfigData config)
{
if (_services.ContainsKey(serviceId))
{
return $"Service {serviceId} is already running.";
}
var service = new MyBackgroundService(serviceId, config);
_services.TryAdd(serviceId, (service, config));
Task.Run(() => service.StartAsync());
return $"Service {serviceId} started.";
}
public string StopService(string serviceId)
{
if (_services.TryRemove(serviceId, out var serviceTuple))
{
serviceTuple.Item1.Stop();
return $"Service {serviceId} stopped.";
}
return $"Service {serviceId} not found.";
}
public string UpdateServiceConfig(string serviceId, ConfigData newConfig)
{
if (_services.TryGetValue(serviceId, out var serviceTuple))
{
serviceTuple.Item1.UpdateConfig(newConfig);
_services[serviceId] = (serviceTuple.Item1, newConfig); // Update config in dictionary
return $"Service {serviceId} updated with new config.";
}
return $"Service {serviceId} not found.";
}
public Dictionary<string, ConfigData> GetRunningServices()
{
return _services.ToDictionary(k => k.Key, v => v.Value.Item2);
}
}- StartService refuses a duplicate id, creates the worker, records it, and starts its loop on the thread pool with
Task.Run. It returns straight away, so the prompt stays responsive. - StopService removes the entry and cancels the worker in one step with
TryRemove. - UpdateServiceConfig pushes the new config into the running worker and updates the stored copy.
- GetRunningServices returns a snapshot, a plain dictionary copy, so the caller can loop over it while workers are added or removed.
#5. The Command Loop
Program.cs reads a line, splits it on spaces and switches on the first word. Each branch validates its arguments and calls the manager. Here is START:
case "START":
if (parts.Length < 4)
{
Console.WriteLine("Usage: START <ServiceID> <Interval(ms)> <ConfigValue>");
break;
}
string serviceId = parts[1];
if (!int.TryParse(parts[2], out int interval))
{
Console.WriteLine("Invalid interval.");
break;
}
string configValue = parts[3];
ConfigData config = new ConfigData { Interval = interval, CustomValue = configValue };
Console.WriteLine(serviceManager.StartService(serviceId, config));
break;A typical session:
Dynamic Background Service Manager
Available Commands: START <id> <interval> <config>, STOP <id>, UPDATE <id> <interval> <config>, LIST, EXIT
Enter command: START a 1000 hello
Service a started.
Service a started. Interval: 1000 ms, Config: hello
Service a is running with config: hello
Service a is running with config: hello
Enter command: UPDATE a 200 fast
Service a updated: Interval=200 ms, Config=fast
Service a updated with new config.
Service a is running with config: fast
Service a is running with config: fast
Enter command: LIST
Running Services:
- a: Interval=200, Config=fast
Enter command: STOP a
Service a stopped.#6. Taking It Further
The console is only one front end. Ideas for a production version:
- Expose it as an API. Register
BackgroundServiceManageras a singleton in ASP.NET Core and mapPOST,PUT,DELETEandGETendpoints to start, update, stop and list, so other systems can control workers. - Stop cleanly on shutdown. An
IHostedServicecan stop every worker when the app exits, and the manager can keep each worker's task so a stop can wait for it to finish. - Apply updates immediately. A new interval takes effect after the current wait ends; cancelling the current
Task.Delaywith a second "wake" token applies it at once. - Treat stopping as normal.
Task.DelaythrowsOperationCanceledExceptionwhen cancelled; catching it (with cleanup infinally) lets the worker log its own "stopped" line. - Guard concurrent starts. Using the return value of
TryAddas the duplicate check keeps two simultaneousSTARTs from both launching a worker. - Persist the workers. Save ids and configs to a database so workers come back after a restart.