Search code examples
c#asp.net-corebackground-service

How to run background service at eveytime i click the Controller (GetAllUsers)


Actually iam trying to run my controller and backgroundService at the same time. But my controller want to execute the background service at each time when iam getting the GetAllUsers. My Controller want to give results without waiting for the end of the await in BackgroundService.( I want to run my background service in parallel).

This is my sample code of UserController

private readonly ILogger<UsersController> _logger;

public UserController(ILogger<UserController> logger)
{
  _logger = logger;
}

[HttpGet]

public async Task<IActionResult> GetAllUsers(CancellationToken stoppingToken)

{
     _logger.LogInformation("MyBackgroundService Started at: {time}", DateTimeOffset.Now);

     await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);  

     _logger.LogInformation("Executing user Donnes");

     List<UserDto> user = listUsers;

     await StopAsync(stoppingToken);

     return new OkObjectResult(user);

}

private async Task StopAsync(CancellationToken cancellationToken)
{
   _logger.LogInformation("MyBackgroundService stopped at: {time}", DateTimeOffset.Now);
   await StopAsync(stoppingToken);
}

Solution

  • I don't think mix up backgroudservice and controller is a good idea. You could try following sample which start and stop a backgroundservice from a controller.
    ServiceProviderExtensions.cs

        public static class ServiceProviderExtensions
        {
            public static TWorkerType GetHostedService<TWorkerType>
                (this IServiceProvider serviceProvider) =>
                serviceProvider
                    .GetServices<IHostedService>()
                    .OfType<TWorkerType>()
                    .FirstOrDefault();
        }
    

    myservice.cs

        public class myservice : BackgroundService
        {
    
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    Console.WriteLine("myservice running");
                    await Task.Delay(1000, stoppingToken);
                }
                await Task.CompletedTask;
    
            }
    
        }
    

    program.cs

    builder.Services.Configure<HostOptions>(hostOptions =>
    {
        hostOptions.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
    });
    builder.Services.AddHostedService<myservice>();
    

    Controller

        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            [HttpGet("stop")]
            public async Task testStop()
            {
                var worker = HttpContext.RequestServices.GetHostedService<myservice>();
    
                await worker.StopAsync(new CancellationToken());
            }
            [HttpGet("start")]
            public async Task testStart()
            {
                var worker = HttpContext.RequestServices.GetHostedService<myservice>();
    
                await worker.StartAsync(new CancellationToken());
            }
        }
    

    Test enter image description here