Out Of Memory Exception Simulation and Profiling

21 בJanuary 2015

אין תגובות

,If that was happened to you, mining you are in deep problem

?But, my point is different. what if it came from no were and not a clue why

The biggest problem is that sometime when the exception is deep, you just cannot debug your

.app anymore

So maybe if we could get information a second before this exception , something like => ” hey

“…dude watch out ! its about memory ending

:That leading to next idea

public static void ProccesProfiler()


            Timer timer = new Timer();

            timer.Interval = 1000;

            timer.Elapsed += timer_Elapsed;



  static void timer_Elapsed(object sender, ElapsedEventArgs e)


            ObjectQuery q = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(q);

            ManagementObjectCollection results = searcher.Get();

            int total = 0;

            int free = 0;

            int inuse =0;

            int usagePercentage;

            foreach (ManagementObject result in results)


                total = Convert.ToInt32(result["TotalVirtualMemorySize"]);

                free = Convert.ToInt32(result["FreeVirtualMemory"]);

                inuse = (total-free);



            Console.WriteLine("at        :" + DateTime.Now.ToLongTimeString());

            Console.WriteLine("total     :" + total);

            Console.WriteLine("free      :" + free);

            Console.WriteLine("in use    :" + inuse);

            usagePercentage = ((inuse * 100) / total) * 100 / 100;

            Console.WriteLine("in use percentage   :" + usagePercentage);

            // system free buffer is about 65 perc..

            if (usagePercentage >= 45)


                    Console.WriteLine("! ! ! ! ! !    W A R N I N G   ! ! ! ! ! !");




.That function can profiling your system virtual memory

:What we need now is to simulate a memory problem like this

public static void DrinkMemory()


            List<byte[]> Memory = new List<byte[]>();

            while (true)


                byte[] item = new byte[2];




And just run all of it together:

static void Main(string[] args)






the ManagementObjectCollection class holds a collection of type ManagementObject

which is a bridge to the windows management system in in our case we just need some info

.about the current memory available per debugging app

.This is of course not a permanent value , and must be depends per platform, and configuration

But even for beginners , when using this function you can reach your specific boundaries before

..the crushing

!Good Luck

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *