-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathDataCacheManager.cs
More file actions
83 lines (71 loc) · 2.87 KB
/
DataCacheManager.cs
File metadata and controls
83 lines (71 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using Microsoft.GS.DPS.Storage.Document;
using Timers =System.Timers;
namespace Microsoft.GS.DPS.API.UserInterface
{
public class DataCacheManager
{
private readonly DocumentRepository _documentRepository;
private Dictionary<string, List<string>> _keywordCache;
private readonly Timers.Timer _cacheTimer;
private readonly object _cacheLock = new object();
public DataCacheManager(DocumentRepository documentRepository)
{
_documentRepository = documentRepository;
_keywordCache = new Dictionary<string, List<string>>();
_cacheTimer = new Timers.Timer(5 * 60 * 1000); // 5 minutes
_cacheTimer.Elapsed += async (sender, e) => await RefreshCacheAsync();
_cacheTimer.Start();
}
public async Task<Dictionary<string, List<string>>> GetConsolidatedKeywordsAsync()
{
if (_keywordCache.Count == 0)
{
await RefreshCacheAsync();
}
lock (_cacheLock)
{
return new Dictionary<string, List<string>>(_keywordCache);
}
}
public async Task RefreshCacheAsync()
{
var consolidatedKeywords = new Dictionary<string, List<string>>();
var documents = await _documentRepository.GetAllDocuments();
foreach (var document in documents.Where(d => d.Keywords != null))
{
foreach (var keywordDict in document.Keywords)
{
if (!consolidatedKeywords.ContainsKey(keywordDict.Key))
{
consolidatedKeywords[keywordDict.Key] = new List<string>();
}
var values = keywordDict.Value.Split(',').Select(v => v.Trim()).ToArray();
foreach (var value in values)
{
if (!consolidatedKeywords[keywordDict.Key].Contains(value))
{
consolidatedKeywords[keywordDict.Key].Add(value);
}
}
consolidatedKeywords[keywordDict.Key] = consolidatedKeywords[keywordDict.Key].OrderBy(v => v).ToList();
}
}
consolidatedKeywords = consolidatedKeywords.OrderBy(k => k.Key).ToDictionary(k => k.Key, v => v.Value);
lock (_cacheLock)
{
_keywordCache = consolidatedKeywords;
}
}
public void ManualRefresh()
{
_cacheTimer.Stop();
_cacheTimer.Start();
Task.Run(async () => await RefreshCacheAsync());
}
}
}