Forward all cancellation tokens and run the local cache first

This commit is contained in:
Jeff Leung 2024-01-08 10:22:51 -08:00
parent c43b218974
commit 5fec5f4f92
1 changed files with 11 additions and 10 deletions

View File

@ -6,7 +6,6 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache
{
public class GeoFeedCacheService : IHostedService
{
CancellationToken _cancellationToken;
private readonly ILogger<GeoFeedCacheService> logger;
private readonly IGeoFeedProvider feedProvider;
private readonly IHost host;
@ -22,7 +21,7 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache
public Task StartAsync(CancellationToken cancellationToken)
{
_ = StartPerioidicSync();
_ = StartPerioidicSync(cancellationToken);
return Task.CompletedTask;
}
@ -31,14 +30,13 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache
return Task.CompletedTask;
}
public async Task<bool> StartPerioidicSync()
public async Task<bool> StartPerioidicSync(CancellationToken Token)
{
await DBContextMigrate();
List<GeoFeedCacheEntry> geoFeedCacheEntry = [];
while (!_cancellationToken.IsCancellationRequested)
while (!Token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(30));
logger.LogInformation("Running on disk fallback cache process...");
try
{
@ -63,13 +61,14 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache
{
dbContext.GeoFeedCacheEntries.RemoveRange(dbContext.GeoFeedCacheEntries.ToArray());
}
await dbContext.AddRangeAsync(geoFeedCacheEntry);
await dbContext.SaveChangesAsync();
await dbContext.AddRangeAsync(geoFeedCacheEntry, Token);
await dbContext.SaveChangesAsync(Token);
}
catch (Exception ex)
{
logger.LogWarning("On disk cache failed to run. Waiting on 30 minutes before retry...");
}
await Task.Delay(TimeSpan.FromMinutes(30));
}
return false;
@ -79,11 +78,13 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache
{
using IServiceScope scope = host.Services.CreateScope();
using GeoFeedCacheDbContext? dbContext =
host.Services.GetService<GeoFeedCacheDbContext>();
if (dbContext.Database.GetPendingMigrations().Any())
{
scope.ServiceProvider.GetService<GeoFeedCacheDbContext>();
#pragma warning disable CS8602 // Dereference of a possibly null reference.
if (dbContext.Database.GetPendingMigrations().Any()) {
await dbContext.Database.MigrateAsync();
}
#pragma warning restore CS8602 // Dereference of a possibly null reference.
}
}
}