Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Challenge: The Loop That Leaks

DZone 's Guide to

Challenge: The Loop That Leaks

This code exercise challenges you to find the loop that leaks...we'll reveal the answer tomorrow!

· Performance Zone ·
Free Resource

Consider the following code:

class Program
{
    static ManualResetEvent _produce = new ManualResetEvent(false);
    static ManualResetEvent _consume = new ManualResetEvent(false);
    private static void Run()
    {
        while (true)
        {
            _produce.WaitOne();
            _produce.Reset();

            var b = new byte[1024 * 1024 * 128];
            MD5.Create().ComputeHash(b);
            b = null;
            Console.WriteLine("Done");
            _consume.Set();
        }
    }

    static void Main(string[] args)
    {
        new Thread(Run)
        {
            IsBackground = true,
        }.Start();

        while (true)
        {
            _produce.Set();
            _consume.WaitOne();
            _consume.Reset();
            GC.Collect(2);
            GC.WaitForPendingFinalizers();
            Console.WriteLine(GC.GetTotalMemory(true));
            Console.ReadLine();
        }
    }
}

Can you tell me what the output will be? And why? Analyze this code and we will go over the answer in the next post, tomorrow!

Topics:
performance ,code analysis ,c# ,memory leaks ,loops

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}