CouchbaseNetClient 2.0.3.1中使用C#客户端的内存使用率过高

时间:2015-04-24 19:18:25

标签: c# memory couchbase

我正在使用CouchbaseNetClient 2.0.3.1进行C#客户端,并在开始线程化应用程序时遇到内存不足的情况。虽然我没有尝试识别每个可疑情况,但我创建了一个简单的场景,演示了我认为过多的内存使用情况。

我的Couchbase服务器有一个完全空的存储桶。从我的C#客户端,我打开一个桶,我很惊讶地看到我的应用程序的内存使用量此时超过了340 MB。现在桶已打开,我尝试从数据库中删除10个无效项。内存使用率保持不变。然后我开始同时删除项目,并开始看到内存使用量的增加,并看到它最终在1 GB左右。

我担心周围的高内存使用率,但同时处理似乎不是我所看到的选项。我可以采取哪些措施来防止这种高内存使用,或者这是一个可以解决的问题吗?

class Program
{
    static void PrintMemoryUsage(string label)
    {
        var mb = 1024 * 1024;
        var gc = GC.GetTotalMemory(true) / mb;
        var pm = Process.GetCurrentProcess().PagedMemorySize64 / mb;
        Console.WriteLine($"{label}:  GC={gc} MB  PM={pm} MB");
    }

    static void ExampleOfThreadedMemoryIssue()
    {
        var cluster = new Couchbase.Cluster();
        var poolConfig = cluster.Configuration.PoolConfiguration;
        poolConfig.MaxSize = Environment.ProcessorCount;
        poolConfig.BufferSize = 1024 * 1024 * 20;
        PrintMemoryUsage("Created a cluster");

        var bucket = cluster.OpenBucket("default");
        PrintMemoryUsage("Opened a bucket");

        for (int i = 0; i < 10; ++i)
        {
            bucket.Remove("CompletelyInvalidKey");
        }
        PrintMemoryUsage("Removed 10 items serially");

        for (int concurrent = 1; concurrent <= 10; ++concurrent)
        {
            var tasks = new List<Task>();
            for (int i = 0; i < concurrent; ++i)
            {
                tasks.Add(Task.Run(() =>
                {
                    bucket.Remove("CompletelyInvalidKey");
                }));
            }
            Task.WaitAll(tasks.ToArray());
            PrintMemoryUsage($"Removed {concurrent} items concurrently");
        }

        Console.WriteLine("\nPress any key to continue.");
        Console.ReadKey(false);
    }
    static void Main(string[] args)
    {
        ExampleOfThreadedMemoryIssue();
    }
}

以下是在我的机器上运行此示例的结果:

Created a cluster:  GC=0 MB  PM=18 MB
Opened a bucket:  GC=321 MB  PM=346 MB
Removed 10 items serially:  GC=321 MB  PM=346 MB
Removed 1 items concurrently:  GC=321 MB  PM=346 MB
Removed 2 items concurrently:  GC=481 MB  PM=508 MB
Removed 3 items concurrently:  GC=641 MB  PM=668 MB
Removed 4 items concurrently:  GC=801 MB  PM=829 MB
Removed 5 items concurrently:  GC=961 MB  PM=991 MB
Removed 6 items concurrently:  GC=961 MB  PM=991 MB
Removed 7 items concurrently:  GC=961 MB  PM=990 MB
Removed 8 items concurrently:  GC=961 MB  PM=990 MB
Removed 9 items concurrently:  GC=961 MB  PM=990 MB
Removed 10 items concurrently:  GC=961 MB  PM=990 MB

Press any key to continue.

1 个答案:

答案 0 :(得分:0)

内存使用量过大是因为您配置的缓冲池大小:1024 * 1024 * 20(MaxSize的倍数)

 poolConfig.BufferSize = 1024 * 1024 * 20;

默认值是1024 * 16,有什么理由增加这个? Couchbase Server支持的最大文档大小为20MB。