Skip to content

Instantly share code, notes, and snippets.

@ngohungphuc
Created November 23, 2018 10:56
Show Gist options
  • Save ngohungphuc/07699fe9171aae66d88ed891357b00be to your computer and use it in GitHub Desktop.
Save ngohungphuc/07699fe9171aae66d88ed891357b00be to your computer and use it in GitHub Desktop.
public class ExampleGuidService : BackgroundService
{
public const string ExampleGuidsKey = "ExampleGuids";
private IMemoryCache memoryCache;
public ExampleGuidService(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
GenerateNewExampleGuid();
await Task.Delay(1000 * 10, stoppingToken);
}
}
private void GenerateNewExampleGuid()
{
ExampleGuid example = new ExampleGuid
{
Timestamp = DateTime.Now,
Guid = Guid.NewGuid()
};
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(24));
if (!this.memoryCache.TryGetValue(ExampleGuidService.ExampleGuidsKey, out List<ExampleGuid> cacheEntry))
{
cacheEntry = new List<ExampleGuid>();
}
cacheEntry.Add(example);
this.memoryCache.Set(ExampleGuidService.ExampleGuidsKey, cacheEntry, cacheEntryOptions);
}
}
public class ExampleGuid
{
public Guid Guid { get; set; }
public DateTime Timestamp { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment