如何衡量.NET内存缓存4.0电流的大小? [英] How to measure current size of .NET Memory Cache 4.0?

查看:182
本文介绍了如何衡量.NET内存缓存4.0电流的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我们正在使用的.NET内存缓存4.0高速缓存的要求。 (不是ASP.NET缓存,没有任何外部缓存)

Currently we're using the .NET Memory Cache 4.0 for the Caching requirements. (not ASP.NET Cache, not any external Cache)

综观.NET内存高速缓存4.0的性能计数器,还有周围的数据缓存命中,未命中,项,辅料等,但没有涉及到大小。

Looking at the '.NET Memory Cache 4.0' performance counters, there is data around Cache Hits, Misses, Entries, Trims etc. but nothing related to Size.

时有测量/知道电流的大小由所使用的缓存的一种方式生产中的应用

Is there is a way of measuring/knowing the current size of the Cache used by the Production Application?

我希望能够捕获在不同的点这个数据在时间和得到高速缓存的平均尺寸。

I want to be able to capture this data at various points in time and get the average size of the cache.

推荐答案

这是一个丑陋的实现细节,微软不希望在所有的暴露。在.NET中测量对象的尺寸不是一般的可能。的MemoryCache使用一个相当讨厌的后门来实现其内存限制触发器,它使用CLR的DACCESS组成部分,实际上旨在帮助实现内存分析器。

It is an ugly implementation detail that Microsoft did not want to expose at all. Measuring object sizes in .NET is not in general possible. MemoryCache uses a fairly nasty backdoor to implement its memory limit trigger, it uses the DACCESS component of the CLR, actually intended to help implement memory profilers.

您可以看到它调试因此它不喜欢你不能得到它。你只需要编写非常丑陋的代码通过私有字段挖:

You can see it with the debugger so it isn't like you can't get to it. You just have to write very ugly code to dig through the private fields:

using System;
using System.Reflection;
using System.Runtime.Caching;

public static class MemoryCacheHackExtensions {
    public static long GetApproximateSize(this MemoryCache cache) {
        var statsField = typeof(MemoryCache).GetField("_stats", BindingFlags.NonPublic | BindingFlags.Instance);
        var statsValue = statsField.GetValue(cache);
        var monitorField = statsValue.GetType().GetField("_cacheMemoryMonitor", BindingFlags.NonPublic | BindingFlags.Instance);
        var monitorValue = monitorField.GetValue(statsValue);
        var sizeField = monitorValue.GetType().GetField("_sizedRef", BindingFlags.NonPublic | BindingFlags.Instance);
        var sizeValue = sizeField.GetValue(monitorValue);
        var approxProp = sizeValue.GetType().GetProperty("ApproximateSize", BindingFlags.NonPublic | BindingFlags.Instance);
        return (long)approxProp.GetValue(sizeValue, null);
    }
}



似乎在.NET 4.6.1工作得很好,没有广泛的测试。这是正常拿到土地的层面,就是不依赖于它,因为它可以与任何.NET更新打破。

Seemed to work pretty well on .NET 4.6.1, not extensively tested. This is okay to get the lay of the land, just don't depend on it since it may break with any .NET update.

这篇关于如何衡量.NET内存缓存4.0电流的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆