Search code examples
asp.netasp.net-mvccachingmemorycache

MemoryCache.Default in MVC Disposing Workaround


I am having a hard-time implementing the workaround to the problem with disposing Cache mentioned in this thread MemoryCache Empty : Returns null after being set.

My latest attempt has the following code to get an instance, wrapped as suggested, in a using statement to suppress the cache from being disposed:

private static CacheDl _instance;
public static CacheDl Instance
{
    get
    {
        if (_instance == null)
        {
            using (ExecutionContext.SuppressFlow())
            {
                _instance = new CacheDl();
            }
        }

        return _instance;
    }
}

private static ObjectCache Cache { get { return MemoryCache.Default; } }

Of course this doesn't work.. I have also tried wrapping the Cache 'getter' in something similar but still no deal.

I have also tried specifying a large pollingInterval to suppress the behavior altogether and still no success.

private ObjectCache _cache;
private ObjectCache Cache
{
    get
    {
        using (ExecutionContext.SuppressFlow())
        {
            return _cache ?? (_cache = new MemoryCache("my-cache", new NameValueCollection { { "pollingInterval", "30:00:00" } }));
        }
    }
}

You guessed it, no luck. Any help would be greatly appreciated.

By the way, I have already requested the mentioned Fixpack from Microsoft but not yet heard anything back after 4 hours having submitted the request..

Honestly, I would really prefer that this would be rolled up into an official Windows Update so we wouldn't have to hack around to get this working on non-.NET 4.5 systems.

Update: Specifically, I would like to know how I am meant to implement the recommended work-around. Can someone please show an example of how this can be implemented?


Solution

  • Ended up sorting this out with configuration settings to extend the Cache polling interval sufficient enough that the application pool will recycle before the interval is reached. Had tried doing this in code when constructing a Cache instance but that didn't work out..

    A comment on the relevant Connect issue mentions this as workable hack if you can control your application pool, while another mentions this on the social.msdn forum.

    Connect Issue

    social.msdn

    The configuration setting which increases the polling interval by 30 hours:

    <system.runtime.caching>
        <memoryCache>
            <namedCaches>
                <add name="Default"
                    cacheMemoryLimitMegabytes="0"
                    physicalMemoryLimitPercentage="0"
                    pollingInterval="30:00:00" />
            </namedCaches>
        </memoryCache>
    </system.runtime.caching>