I'm going to use a static collection that will be used for reading by the core process and fully updated every X mins by the background service.
The background process will load updated data from the database every X mins and set the received dataset into this static collection.
The core process will receive many tasks to check if some values exist in this collection. Each task will be processed in a separate thread. There will be a lot of requests, it should be extremely fast, so I can't ask database for each request and I need an updateable list in memory.
public class LoadedData
{
public static HashSet<string> Keys { get; set; }
}
public class CoreProcess
{
public bool ElementExists(string key)
{
return LoadedData.Keys.Contains(key);
}
}
public class BackgroundProcess
{
public async Task LoadData()
{
while (true)
{
LoadedData.Keys = GetKeysFromDb();
await Task.Delay(TimeSpan.FromMinutes(5));
}
}
}
So, I'm looking for the best solution for this.
I was thinking about using HashSet<T>
because I'm sure that each element in the collection will be unique. But HashSet<T>
is not thread-safe. So I started considering BlockingCollection<T>
, ConcurrentBag<T>
, ConcurrentDictionary<T, byte>
, but then I wondered if I needed a thread-safe collection here at all. Looks like not, because I'm not going to add/update/remove particular elements in the collection. Only full rewrite from the database.
So, does it mean that I can just use simple
HashSet<T>
?Which collection would you use to solve it?
And in general, will there be any issues with a simultaneous reading by the core process and full overwriting of the collection by the background process?