Last active
July 3, 2025 21:17
-
-
Save MirzaLeka/f407b3e744b71c4aa8292eaf8b4dc4bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using APIDocsRider.DB; | |
| using Microsoft.Data.SqlClient; | |
| using Microsoft.EntityFrameworkCore; | |
| namespace APIDocsRider.BL; | |
| public class WorkerService(ILogger<WorkerService> logger, IServiceProvider serviceProvider) : BackgroundService | |
| { | |
| private readonly IServiceProvider _serviceProvider = serviceProvider; | |
| private readonly ILogger<WorkerService> _logger = logger; | |
| protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
| { | |
| using var scope = _serviceProvider.CreateScope(); | |
| try | |
| { | |
| // handles service shutdown via deployment or other failures | |
| while (!stoppingToken.IsCancellationRequested) | |
| { | |
| // inject DB context into Hosted Service | |
| var db = scope.ServiceProvider.GetRequiredService<GamesContext>(); | |
| await foreach (var gameTitle in db.GameModes | |
| .Select(g => g.Title) | |
| .AsAsyncEnumerable() // maps records into stream | |
| .WithCancellation(stoppingToken)) | |
| { | |
| _logger.LogInformation("reading: {Game}", gameTitle); | |
| // timeout test | |
| await Task.Delay(TimeSpan.FromSeconds(10)); | |
| _logger.LogInformation("passed timeout: {Game}", gameTitle); | |
| } | |
| // 30 seconds delay between worker restarts | |
| await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); | |
| } | |
| } | |
| // catches worker failures | |
| catch (OperationCanceledException) | |
| { | |
| _logger.LogWarning("Worker was cancelled during processing."); | |
| } | |
| catch (SqlException ex) | |
| { | |
| _logger.LogCritical(ex, "SQL Exception!"); | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.LogCritical(ex, "Critical Exception!"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment