best way in c# to make only one thread to build the resource so that the remaining threads can wait and then later access the resource.
I have a dictionary which needs to be build by a thread for the remain threads to use.
private Dictionary<string, List<A>> _aDictionary;
I have a method which gets or creates the dictionary.
public async Task<List<A>> GetAs(string aId)
{
if (string.IsNullOrWhiteSpace(aId))
{
return default;
}
try
{
if (!_isCached)
{
await lockSem.WaitAsync();
if (!_isCached)
{
await build(); // builds the dictionary
_isCached = true;
lockSem.Release();
}
}
return _aDictionary.TryGetValue(aId, out var a) ? a: default;
}
catch(Exception ex)
{
_logger.Error("Error", ex);
lockSem.Dispose();
return default;
}
}
Others should not access this resource until the _isCached is set. So I looking for suggestions or best practices in this scenario