ThreadLocal的<>和内存泄漏

时间:2011-09-27 09:41:01

标签: .net memory-leaks thread-local

.Net 4. ThreadLocal<>实现IDisposable。但似乎调用Dispose()实际上并没有释放对持有的线程本地对象的引用。

此代码重现了该问题:

using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        class ThreadLocalData
        {
            // Allocate object in LOH
            public int[] data = new int[10 * 1024 * 1024];
        };

        static void Main(string[] args)
        {
            // Stores references to all thread local object that have been created
            var threadLocalInstances = new List<ThreadLocalData>();
            ThreadLocal<ThreadLocalData> threadLocal = new ThreadLocal<ThreadLocalData>(() =>
            {
                var ret = new ThreadLocalData();
                lock (threadLocalInstances)
                    threadLocalInstances.Add(ret);
                return ret;
            });
            // Do some multithreaded stuff
            int sum = Enumerable.Range(0, 100).AsParallel().Select(
                i => threadLocal.Value.data.Sum() + i).Sum();
            Console.WriteLine("Sum: {0}", sum);
            Console.WriteLine("Thread local instances: {0}", threadLocalInstances.Count);

            // Do our best to release ThreadLocal<> object
            threadLocal.Dispose();
            threadLocal = null;

            Console.Write("Press R to release memory blocks manually or another key to proceed: ");
            if (char.ToUpper(Console.ReadKey().KeyChar) == 'R')
            {
                foreach (var i in threadLocalInstances)
                    i.data = null;
            }
            // Make sure we don't keep the references to LOH objects
            threadLocalInstances = null;
            Console.WriteLine();

            // Collect the garbage
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Console.WriteLine("Garbage collected. Open Task Manager to see memory consumption.");
            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

线程本地数据存储对大对象的引用。如果未手动取消引用,GC不会收集这些大对象。我使用任务管理器来观察内存消耗。我也运行内存分析器。垃圾收集后我拍了一张快照。分析器显示泄漏的对象由GCHandle生成,并在此处分配:

mscorlib!System.Threading.ThreadLocal<T>.GenericHolder<U,V,W>.get_Boxed()
mscorlib!System.Threading.ThreadLocal<T>.get_Value()
ConsoleApplication2!ConsoleApplication2.Program.<>c__DisplayClass3.<Main>b__2( int ) Program.cs

这似乎是ThreadLocal&lt;&gt;中的一个缺陷设计。存储所有已分配对象以进一步清理的技巧很难看。关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:1)

内存可能已被垃圾收集,但CLR进程还没有放弃它。它倾向于在稍后需要的时候保留分配的内存,因此它不必进行昂贵的内存分配。

答案 1 :(得分:1)

在.Net 4.5 DP上运行,我认为在您的应用程序中按 R 之间没有任何区别。如果4.0中确实存在内存泄漏,那么它似乎已修复。

(4.5是就地更新,因此我无法在同一台计算机上测试4.0,抱歉。)