Tasks are not getting destroyed and filling up memory

  c++, windows, winforms

Consider this simple example program that puts ints into a list:

void Main()
{
    Experiment experiment = new();
    var task = Task.Run(experiment.Start);
}

public class Experiment
{
    public async Task Start()
    {
        List<int> values = new();

        for (int i = 0; i < 1000000000; i++)
            values.Add(i);

        await Task.CompletedTask;
    }
}

When run this uses about 7 GB of memory. But then that data just stays there. Even if I clear the list or set it to null, the program still takes up 7 GB. When I run it again, the RAM usage suddenly goes down to 10 MB and then shoots up to 7 GB again, making me think that only if I start a new tasks with this method, the data is actually released.

Why does the memory not get released when the task is done? I don’t understand why the list is not temporary and keeps occupying memory. What am I doing wrong?

Source: Windows Questions

LEAVE A COMMENT