Created
November 23, 2018 10:56
-
-
Save ngohungphuc/07699fe9171aae66d88ed891357b00be 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
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