I have a method initializing an in-memory cache of some objects that is called before entering said cache. To the best of my knowledge I have used a SemaphoreSlim correctly but still several times the semaphore has locked up and no threads have been able to access the block. Is there any way that the lock release in a finally block could be ignored? We are using .NET 4.6.2, ASP.NET MVC and hosting as an Azure application.
private static readonly SemaphoreSlim _lock = new SemaphoreSlim(1);
private static async Task<bool> InitializeCache()
{
if (Cache != null) return true;
if (await _lock.WaitAsync(30000))
{
try
{
if (Cache != null) return true;
var items = await API.GetKeysFromAPI();
Cache = new ConcurrentDictionary<string, SamlSessionState>(items);
return true;
}
catch (Exception e)
{
throw new Exception("Error initializing the cache", e);
}
finally
{
_lock.Release();
}
}
else
{
// This keeps getting called after the semaphore locks up.
throw new Exception("Error initializing the cache, the semaphore timed out.");
}
}
I would expect that the finally block would be called every time. Could the request being terminated stop the execution so that finally block is never called?