I am trying to add a start and stop functionality to a long-running background service in my Blazor server app by the press of a button(s). The background service, PeriodicExecutor
, is started without any user interaction in the startup.cs file and works as expected:
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHostedService<PeriodicExecutor>();
}
Below is the essential code in the background service:
PeriodicExecutor.cs
public class PeriodicExecutor : BackgroundService
{
protected override async Task ExecuteAsync(System.Threading.CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(5000);
}
}
}
Below is the essential code in the base class that handles the code for the button onclick()
events:
IndexBase.cs
public class IndexBase : ComponentBase
{
[Inject]
IJSRuntime JSRuntime { get; set; }
protected override void OnInitialized()
{
}
protected async Task StartService()
{
if (!PeriodicExecutor.status)
{
await JSRuntime.InvokeVoidAsync("alert", "Microservice Started");
}
else
{
await JSRuntime.InvokeVoidAsync("alert", "Microservice Already Running");
}
}
protected async Task StopService()
{
if (PeriodicExecutor.status)
{
await JSRuntime.InvokeVoidAsync("alert", "Microservice Stopped");
}
else
{
await JSRuntime.InvokeVoidAsync("alert", "Microservice Already Stopped");
}
}
}
So the question is, how can i stop the backgroundservice with a cancellation token from the StopService()
method and start the background service in the StartService()
method? Any detailed answers would be greatly appreciated.