Search code examples
c#multithreadingasp.net-corememory-leaksgarbage-collection

why creating these threads don't free memory?


I've such a code:

class Engine
{
    private static Thread f_thread;
    private static System.Timers.Timer timeWatch;

    public static void Start()
    {
        try
        {
            timeWatch = new System.Timers.Timer(30000);
            timeWatch.Elapsed += FolderMonitor;
            timeWatch.AutoReset = true;
            timeWatch.Enabled = true;
        }
        catch (Exception ex)
        {
            // catch error
        }
    }

    public static void FolderMonitor(object source, ElapsedEventArgs e)
    {
        f_thread = new Thread(FileScan);
        f_thread.Start();
    }


    public static void FileScan()
    {
        if (timeWatch != null)
        {
            timeWatch.Stop();
        }

        try
        {
            // some operations
        }
        catch (Exception ex)
        {
            // catch error
        }

        timeWatch.Start();
    }
}

on a .NET Core 2.2 Windows Service that run on a remote machine. If I check the memory after 1 week of running, it constantly grow up.

It seems it doesn't free the memory allocated by thread (some sort of memory leaks).

But also if I do "nothing" within the thread's FileScan function, it grow up (lesser, but id does). What is happening? Shouldn't GC free it up automatically?


Solution

  • Static objects and variables belonging to those object (i.e. the thread you create and run) don't get garbage collected in C#.

    For the thread to be garbage collected, it must belong to a non-static object, must be stopped and all the references cleared (mythread = null).

    I've had the same problem using threads, writing an audio streaming dedicated server in C#.

    When i discovered the leak, i had to re-think and re-write a big part of the code. :)