17,740
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Threading;
namespace crazyMemory1
{
class Program
{
static void Main(string[] args)
{
// withOUT these two lines, GC also worked almost
// well --- it reached >1.2GB then dropped back to
// hundreds MB without exception throwing.
byte[] nop = new byte[800 * 1048576];
Program inst = new Program();
// go
Thread thread = new Thread(inst.threadProc);
thread.Start();
// press ENTER to quit
Console.ReadKey();
// stop it
inst.m_stop.Set();
thread.Join();
}
private ManualResetEvent m_stop = new ManualResetEvent(false);
private AutoResetEvent m_clock = new AutoResetEvent(false);
private enum EVENT_INDEX { STOP, CLOCK };
private void onTimer(object input)
{
m_clock.Set();
}
private void threadProc()
{
Timer timer = new Timer(onTimer, null, 0, 500);
WaitHandle[] events = { m_stop, m_clock };
while (true)
{
EVENT_INDEX wait = (EVENT_INDEX)WaitHandle.WaitAny(events, Timeout.Infinite);
if (EVENT_INDEX.STOP == wait)
break;
else if (EVENT_INDEX.CLOCK == wait)
memoryEater();
}
timer.Dispose();
}
private void memoryEater()
{
try
{
byte[] buf = new byte[30 * 1048576];
// withOUT these two lines, GC also worked
// almost well --- it reached >1.9GB then
// dropped back to hundreds MB without exception
// throwing.
byte bvalue = Convert.ToByte((new Random()).Next(0, 255));
Array.ForEach(buf, b => b=bvalue);
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
return;
}
Console.WriteLine("memory allocated");
}
}
}