相关疑难解决方法(0)

ThreadLocal <>和内存泄漏

.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;
            }); …
Run Code Online (Sandbox Code Playgroud)

.net memory-leaks thread-local

8
推荐指数
1
解决办法
1535
查看次数

标签 统计

.net ×1

memory-leaks ×1

thread-local ×1