简体   繁体   中英

Dead objects eating up memory

Within my application, I'm having memory usage issues where the Loh is filling up with dead objects, 1.5GB worth (seen below). The objects are being stored in a Byte array.

在此处输入图片说明

I've tried to clean it up by running the following code to reduce memory usage but it doesn't seem to be functioning.

private static void OnScavengeProfileCache(object data)
{
 // loop until the runtime is shutting down
while(HostingEnvironment.ShutdownReason == ApplicationShutdownReason.None)
{
    // NOTE: Right now we only do the scavenge when traffic is temporarily low,
    // to try to amortize the overhead of scavenging the cache into a low utilization period.
    // We also only scavenge if the process memory usage is very high.
    if (s_timerNoRequests.ElapsedMilliseconds >= 10000)
    {
        // We dont want to scavenge under lock to avoid slowing down requests,
        // so we get the list of keys under lock and then incrementally scan them
        IEnumerable<string> profileKeys = null;
        lock (s_profileCache)
        {
             profileKeys = s_profileCache.Keys.ToList();
        }


        ScavengeProfileCacheIncremental(profileKeys.GetEnumerator());
    }

    // wait for a bit
    Thread.Sleep(60 * 1000);
}
}

private static void ScavengeProfileCacheIncremental(IEnumerator<string> profileKeys)
{
if (s_thisProcess.PrivateMemorySize64 >= (200 * 1024 * 1024) ) // 3Gb at least
{
    int numProcessed = 0;
    while(profileKeys.MoveNext())
    {
        var key = profileKeys.Current;
        Profile profile = null;
        if (s_profileCache.TryGetValue(key, out profile))
        {
            // safely check/remove under lock, its fast but makes sure we dont blow away someone currently being addded
            lock (s_profileCache)
            {
                if (DateTime.UtcNow.Subtract(profile.CreateTime).TotalMinutes > 5)
                {
                    // can clear it out
                    s_profileCache.Remove(key);
                }
            }
        }

        if (++numProcessed >= 10)
        {
            // stop this scan and check memory again
            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect(); 
            break;
        }
    }
}
}

Any tips on how I should go about cleaning up memory usage here?

try System.GC.Collect() forces garbage collector to run. This should clean out dead objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM