Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Avoid Caching with MemoryCache and GetOrCreate in .NET

Avoid Caching with MemoryCache and GetOrCreate in .NET
December 8, 2022 2 min read BEN ABT
.NET

This article was written in 2022. Versions, tools and recommendations may have changed since then. Newer posts are collected under .NET.

GetOrCreate or its asynchronous counterpart GetOrCreateAsync is an extension method to create a cache entry if it does not exist yet.

This method takes a key and a function that is used to create the object and it returns the object that is stored in the cache for the specified key. If the object does not exist in the cache, the function will be called to create the object, which will then be added to the cache and returned by the GetOrCreate method.

The problem: in principle every result of the delegate is added to the cache, which is sometimes, with certain values then nevertheless not desired.

If we do not want to cache null values in a scenario: at first glance, it does not seem to work without a workaround. You see various workarounds on the net to simply set the ExpiredOn time point in the past, but is that really so great?

C#
entry.AbsoluteExpirationRelativeToNow = TimeSpan.Zero;

But a look into the source code reveals that Dispose() is the solution:

Each cache entry is surrounded by ICacheEntry, which implements Disposable and is used in the implementation of MemoryCache to remove an entry. So, lets dispose the entry!

C#
 1
 2string cacheKey = "My.Cache.Key." + userId;
 3
 4// get entry from cache or request and store in cache
 5CustomerDataModel? customerData = await _cache.GetOrCreateAsync(cacheKey, async (cacheEntry) =>
 6{
 7    // get data
 8    ApiResponse<CustomerDataModel> anyResponse = await _myHttpClient.GetFromApiEndpoint(userId).ConfigureAwait(false);
 9
10    CustomerDataModel? data = anyResponse.Data;
11
12    // if data is null, dont cache
13    if (data is null)
14    {
15        cacheEntry.Dispose();
16        return null;
17    }
18
19    // if data is not null, cache for ever
20    //    you can also set the expiration here
21    return data;
22
23    // This works!
24}).ConfigureAwait(false);

Pitfalls

Setting a value must not be done before the Dispose, otherwise the entry will end up in the cache after all!

C#
1cacheEntry.Value = data; // <<-- dont do that
2cacheEntry.Dispose();

Conclusion

Dispose seems to be the perfect way here, even though I couldn’t find any documentation on the behavior. In principle, however, it is a documented API and since the Dispose behavior is not internal, one can expect that this behavior will not change for the time being, but that the behavior will remain stable and can thus also be used in productive scenarios.

Thanks also to gfoidl , who gave me the decisive tip.

Related articles

Production Rate Limiting in ASP.NET Core

Nov 3, 2026 - 16 min read

Production Rate Limiting in ASP.NET Core

Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

The Big Decimal Bugfix with .NET 11

Nov 2, 2026 - 11 min read

The Big Decimal Bugfix with .NET 11

For more than two decades, (decimal)1.23 returned 1.23m. It looked correct, it passed every test and it was a polite lie.

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026 - 10 min read

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled and Alpine are often compared as three equivalent Linux distributions. They are not. Alpine is a distribution built …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Automating Microsoft Entra External ID: CIAM Provisioning and Branding

Automating Microsoft Entra External ID: CIAM Provisioning …

Nov 10, 2026
Production Rate Limiting in ASP.NET Core

Production Rate Limiting in ASP.NET Core

Nov 3, 2026
The Big Decimal Bugfix with .NET 11

The Big Decimal Bugfix with .NET 11

Nov 2, 2026
Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026

Tags

.NET (195) Csharp (99) ASP.NET Core (49) Azure (42) DevOps (17) Docker (15) Microsoft (14) Security (12) EF Core (11) Microsoft MVP (11) AI (10) GitHub (10) GitHub Copilot (10) Architecture (9) ASP.NET (9) Synology (9) .NET 11 (8) Raspberry (8) Azure Functions (7) Cloudflare (7)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact