MemoryCache doesn’t persist when attached to Visual Studio Debugger

With .NET 4.0, System.Runtime.Caching MemoryCache can be used to persist large object collections for better performance. This works great when your web application is published to a server. When debugging in Visual Studio, you’ll find that the cache object will be empty at random times. This is apparently caused by a bug in .NET 4.0. The problem has been fixed in .NET 4.5 and above but for those still using 4.0 this problem can be a pain in ass when debugging your application.
Microsoft released a Hotfix for .NET 4.0 but it has to be requested from their Hotfix Request Form. There is no official documentation of this bug anywhere except for a short post by Scott Hanselman on StackOverflow.
Luckily, there’s a workaround to get this working in .NET 4.0. The MemoryCache seems to be tied to a thread context. When the thread context is no longer available, the MemoryCache stops working. To get around this problem retrieve your MemoryCache under disabled execution context flow:

using (ExecutionContext.SuppressFlow()) {
        _cache = MemoryCache.Default;
}

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please Do the Math      
 

*