Almeida Juan
Almeida Juan

Reputation: 69

Memory usage in infinite loop

I'm curious how much memory an infinite loop uses on my computer. I know it depends what the Thread is doing, but let's say it's reading some Json and parsing the string with a regex. Does this store junk in the memory with every loop?

public  void loadCookie()
{
    Thread myT = new Thread(() =>
    {
        while (true)
        {
            getUserID();
            Thread.Sleep(0);
        }  
    });

    myT.IsBackground = true;
    myT.Start();
}

Upvotes: 0

Views: 921

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

Disregarding any other problem and just focusing on your memory.

The answer is every allocation (strangely enough) allocates memory. You can assume if you call just about any method there will be allocations, how many depends on the method. However, .net is built with a garbage collector that will monitor this issue and (when it feels the need) will clean up and or compact your out of scope allocations.

Garbage collection isn't free, meaning, it pauses all your threads to do its job, so in certain situations this might not be ideal. however in the majority of the time it's not a big deal.

If you are worried about allocations, or want to keep pressure off the GC, then you need to monitor your memory, I suggest one of many memory profilers to work out what's been allocated and do some research on the garbage collector and how it works.

Upvotes: 2

Theodor Zoulias
Theodor Zoulias

Reputation: 43464

Insert this line inside the loop to find out!

Console.WriteLine($"Mem usage: {GC.GetTotalMemory(true):#,0} bytes");

Upvotes: 1

Related Questions