I have asp.net app with worker service initialized like this.
builder.Services.AddHostedService<XXX>();
And then service worker itself.
public class XXX : BackgroundService
{
readonly ILogger<XXX> _logger;
public XXX(ILogger<XXX> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service Started.");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service Stopped.");
return Task.CompletedTask;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
new MyInfiniteLoopClass();
}
}
In method ExecuteAsync I am creating class MyInfiniteLoopClass which consist of infinity loop lets say while(true)
.
Problem is that swagger runs only when I break that infinity cycle. Which means that entire asp.net app stops on that method. How can I make side by side?
This is a known issue in ASP.NET Core.
You can add await Task.Yield()
to the top of the ExecuteAsync()
and it will work:
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Yield();
new MyInfiniteLoopClass();
}