Shuxia Ning
2024-11-06 adf8dc1c7cae1b12f486dcdb3d7daf4a5a59ec52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Reflection;
 
namespace IStation
{
    internal sealed partial class SharedMemoryCache
    {
        /// <summary>
        /// https://stackoverflow.com/questions/22392634/how-to-measure-current-size-of-net-memory-cache-4-0
        /// </summary>
        /// <returns>Attempts to return the approximate size, otherwize returns -1 for unknown</returns>
        internal long GetApproximateSize()
        {
            long approximateSize;
 
            try
            {
                var statsField = typeof(System.Runtime.Caching.MemoryCache).GetField("_stats", BindingFlags.NonPublic | BindingFlags.Instance);
                var statsValue = statsField.GetValue(this._memoryCache);
 
                var monitorField = statsValue.GetType().GetField("_cacheMemoryMonitor", BindingFlags.NonPublic | BindingFlags.Instance);
                var monitorValue = monitorField.GetValue(statsValue);
 
                var sizeField = monitorValue.GetType().GetField("_sizedRefMultiple", BindingFlags.NonPublic | BindingFlags.Instance);
                var sizeValue = sizeField.GetValue(monitorValue);
 
                var approximateSizeProperty = sizeValue.GetType().GetProperty("ApproximateSize", BindingFlags.NonPublic | BindingFlags.Instance);
 
                approximateSize = (long)approximateSizeProperty.GetValue(sizeValue, null);
            }
            catch
            {
                approximateSize = -1;
            }
 
            return approximateSize;
        }
    }
}