Advertisement
Beginner .NET, Caching (In-Memory, Distributed & Redis)

What does the GetOrCreateAsync pattern accomplish when working with IMemoryCache, and why is it preferred over separate TryGetValue/Set calls?

Short answer

GetOrCreateAsync atomically checks for an existing cache entry and, if missing, invokes a factory delegate to compute and store the value in one operation, resulting in cleaner code than manually calling TryGetValue, checking the result, and then calling Set separately -- and…

Save .NET mock interview
Advertisement
AModel answer
GetOrCreateAsync atomically checks for an existing cache entry and, if missing, invokes a factory delegate to compute and store the value in one operation, resulting in cleaner code than manually calling TryGetValue, checking the result, and then calling Set separately -- and critically, IMemoryCache's implementation of this pattern also provides built-in per-key locking to reduce (though not eliminate under heavy load) cache stampede risk for the same key.
public async Task<Product> GetProductAsync(int id) {
    return await _cache.GetOrCreateAsync($"product-{id}", async entry => {
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15);
        return await _repository.GetByIdAsync(id);
    });
}
Real-world example
A product catalog service consistently uses GetOrCreateAsync throughout its caching code instead of manual TryGetValue/Set pairs, resulting in more concise code and automatic protection against the most common cache-miss race conditions.
Likely follow-ups
  • What does the entry parameter inside the factory delegate let you configure?
  • How does this differ from IDistributedCache, which has no built-in equivalent?
Related topics