1

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.

TriedAtLeast
  • 181
  • 1
  • 10
  • Shouldn't you use a CancellationTokenSource? – Daniel Lozano Mar 15 '22 at 15:10
  • I think the point of a "BackgroundService" is it runs in the background. I don't think you start and stop them from the UI or any other front end process. `ExecuteAsync` and `StopAsync` are called by the service container. If you want some sort of timer process that you control from the UI then why not use a normal service with some control mechanisms? – MrC aka Shaun Curtis Mar 15 '22 at 16:05
  • I didn't try it but this might help; https://stackoverflow.com/questions/51469881/asp-net-core-ihostedservice-manual-start-stop-pause – Cenk Feb 18 '23 at 04:25

0 Answers0