Search code examples
c#multithreading.net-coreparallel.foreachmemory-efficient

Parallel.ForEach memory usage keeps growing


public string SavePath { get; set; } = @"I:\files\";

public void DownloadList(List<string> list)
{
    var rest = ExcludeDownloaded(list);
    var result = Parallel.ForEach(rest, link=>
    {
        Download(link);
    });
}

private void Download(string link)
{
    using(var net = new System.Net.WebClient())
    {
        var data = net.DownloadData(link);

        var fileName = code to generate unique fileName;
        if (File.Exists(fileName))
            return;

        File.WriteAllBytes(fileName, data);
    }
}

var downloader = new DownloaderService();
var links = downloader.GetLinks();
downloader.DownloadList(links);

I observed the usage of RAM for the project keeps growing enter image description here

I guess there is something wrong on the Parallel.ForEach(), but I cannot figure it out.

Is there the memory leak, or what is happening?


Update 1

After changed to the new code

private void Download(string link)
{
    using(var net = new System.Net.WebClient())
    {
        var fileName = code to generate unique fileName;
        if (File.Exists(fileName))
            return;
        var data = net.DownloadFile(link, fileName);
        Track theTrack = new Track(fileName);
        theTrack.Title = GetCDName();
        theTrack.Save();
    }
}

enter image description here

I still observed increasing memory use after keeping running for 9 hours, it is much slowly growing usage though.

Just wondering, is it because that I didn't free the memory use of theTrack file?

Btw, I use ALT package for update file metadata, unfortunately, it doesn't implement IDisposable interface.


Solution

  • Use WebClient.DownloadFile() to download directly to a file so you don't have the whole file in memory.