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

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026 - 11 min read

Containerizing .NET in 2026 Without a Dockerfile

Most .NET Dockerfiles repeat the same five steps: restore, publish, select the matching Microsoft runtime image, copy the output and start …

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026 - 12 min read

Problem Details in ASP.NET Core and .NET 11

builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026 - 11 min read

Resilience in .NET with Microsoft.Extensions.Resilience

Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …


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
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026
Problem Details in ASP.NET Core and .NET 11

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026
Resilience in .NET with Microsoft.Extensions.Resilience

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026
What Matters in ASP.NET Core 11

What Matters in ASP.NET Core 11

Sep 14, 2026

Tags

.NET (192) Csharp (96) ASP.NET Core (48) Azure (41) DevOps (17) Docker (14) Microsoft (14) EF Core (11) Microsoft MVP (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Security (9) Synology (9) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7) Bicep (6)
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