闽公网安备 35020302035485号
dump跨机器分发慢。
public classMemorySpikeSimulator
{
privatestaticreadonly MemoryCache _memoryCache1 = new MemoryCache("Cache1");
privatestaticreadonly MemoryCache _memoryCache2 = new MemoryCache("Cache2");
privatestaticreadonly MemoryCache _memoryCache3 = new MemoryCache("Cache3");
privatestaticreadonly List<byte[]> _staticCache = new List<byte[]>();
public static void Main()
{
Console.WriteLine("模拟内存增长测试...");
Console.WriteLine("初始内存: " + FormatBytes(GC.GetTotalMemory(false)));
// 模拟正常业务操作 - 三个MemoryCache共4GB
SimulateNormalOperations();
Console.WriteLine("正常操作后内存: " + FormatBytes(GC.GetTotalMemory(false)));
Console.WriteLine("按Enter进行 意外内存 分配阶段... ");
Console.ReadLine();
// 模拟意外的大内存分配 - _staticCache增加2GB
SimulateUnexpectedAllocation();
Console.WriteLine("意外分配后内存: " + FormatBytes(GC.GetTotalMemory(false)));
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("GC后内存: " + FormatBytes(GC.GetTotalMemory(true)));
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
private static void SimulateNormalOperations()
{
Console.WriteLine("开始正常内存分配 (三个MemoryCache共4GB)...");
// 堆代码 duidaima.com
// 三个MemoryCache实例共同分配约4GB
for (int i = 0; i < 350; i++) // 增加循环次数以达到4GB
{
var buffer1 = newbyte[4 * 1024 * 1024]; // 4MB
_memoryCache1.Add($"cache1_key_{i}", buffer1, DateTimeOffset.Now.AddHours(1));
var buffer2 = newbyte[4 * 1024 * 1024]; // 4MB
_memoryCache2.Add($"cache2_key_{i}", buffer2, DateTimeOffset.Now.AddHours(1));
var buffer3 = newbyte[4 * 1024 * 1024]; // 4MB
_memoryCache3.Add($"cache3_key_{i}", buffer3, DateTimeOffset.Now.AddHours(1));
if (i % 50 == 0)
{
Console.WriteLine($"已分配: {(i + 1) * 12}MB");
}
Thread.Sleep(10); // 稍微减慢速度
}
}
private static void SimulateUnexpectedAllocation()
{
Console.WriteLine("开始意外内存分配 (_staticCache增加2GB)...");
// _staticCache意外增加约2GB
for (int i = 0; i < 200; i++)
{
var unexpectedData = newbyte[10 * 1024 * 1024]; // 10MB
_staticCache.Add(unexpectedData);
if (i % 20 == 0)
{
Console.WriteLine($"已分配: {(i + 1) * 10}MB");
}
Thread.Sleep(1);
}
}
private static string FormatBytes(long bytes)
{
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int counter = 0;
decimal number = bytes;
// 堆代码 duidaima.com
while (Math.Round(number / 1024) >= 1)
{
number /= 1024;
counter++;
}
return$"{number:n2} {suffixes[counter]}";
}
}




