question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How does the memory cache handle multiple threads entering when the cache is expired?

See original GitHub issue

Summary: What are you wanting to achieve? I’m trying to figure out if my use of a semaphore is even needed.

What code or approach do you have so far?
my policy is basically:

Policy.CacheAsync<T>(cacheProvider: cacheProvider.AsyncFor<T>(),
                    ttl: TimeSpan.FromMinutes(cacheMinutes),
                    onCacheError: onCacheError);
private readonly SemaphoreSlim _usersLock; 
...
_usersLock = new SemaphoreSlim(1, 1); 
...

await _usersLock.WaitAsync(cancellationToken);
try
{                     
    var cacheResult = await _cache.ExecuteAndCaptureAsync(async (_, _) =>
                            await _masterDataApi.GetUserAccountsAsync(new UserAccountLookupDto(), cancellationToken), 
                            new Context(UsersCacheKey), 
                            cancellationToken);
    
    cacheResult.ThrowIfFailure(_masterDataApi.GetType(), nameof(_masterDataApi.GetUserAccountsAsync));
    
    return cacheResult.Result;
}
finally
{
    _usersLock.Release();
}

I did this a while back because I thought if multiple threads tried to read when the cache was expired then I would get multiple http calls. I’m pretty sure I had tested this but it was a few years ago. I was going over my code and got to wondering if this was needed at all anymore (or ever was)?

Issue Analytics

  • State:closed
  • Created 9 months ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
joelhulencommented, Dec 14, 2022

Since you are dealing with potentially multiple instances accessing the same limited resource, I suggest looking into the Distributed Circuit Breaker pattern. This sample project shows how to implement a distributed circuit breaker in Azure Functions (using Durable functions), where you use a circuit breaker id with each call by your instances to share the circuit breaker state. Otherwise, if you don’t share the circuit breaker state, then each instance only knows about its own state and not the state of other instances also trying to access the resource, as you have seen.

My caveat here is that the sample implementation I linked you to is about three years old, so you’ll want to update the SDK versions, but theoretically, it should still work. If you want to go down this path and need some help getting it to work, please let me know.

0reactions
github-actions[bot]commented, Jul 16, 2023

This issue was closed because it has been inactive for 14 days since being marked as stale.

Read more comments on GitHub >

github_iconTop Results From Across the Web

MemoryCache Thread Safety, Is Locking Necessary?
The default MS-provided MemoryCache is entirely thread safe. Any custom implementation that derives from MemoryCache may not be thread safe.
Read more >
Cache in-memory in ASP.NET Core
This can result in several threads repopulating the cached item. When one cache entry is used to create another, the child copies the...
Read more >
NET: Couple words about using MemoryCache
It uses background thread to check lifetime and clean expired entities in a cache. - MemoryCache is thread-safe, but doesn't prevent race ...
Read more >
In-Memory Caching in ASP.NET Core
A good caching strategy is to use a combination of sliding and absolute expiration. Priority – This sets the priority of the cached...
Read more >
ASP.NET Core Memory Cache - Is the GetOrCreate ...
NET Core MemoryCache can be accessed simultaneously by different threads and the threads do not interfere with each other directly.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found