Home > Blockchain >  Tasks are not getting destroyed and filling up memory
Tasks are not getting destroyed and filling up memory

Time:11-26

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?

CodePudding user response:

.NET uses garbage collection to release unused memory.

Garbage collection is more likely to run when memory is getting low. But other than that, there is no way to predict when it will run, or when your memory will be released.

In either case, garbage collection does not run as soon as the memory is no longer needed (or when the task is done in your case).

This is normal behavior. When you're running low on memory, garbage collection should take care of it soon enough.

CodePudding user response:

Maybe add task.Wait() in the main program. I think as written the main program exits before the the task is complete. Maybe the task still is referenced when it exits therefore slowing down the gc.

  • Related