简体   繁体   中英

Memory leak using timers

I have piece of code that the Ants profiler points to that is causing a memory leak. I have monitored the application over a period of 1 week, but the memory seems to be increasing and not coming back. SO I'm a bit concerned with the below code.

      public void printXML(XmlDocument doc)
        {
            //System.Threading.Timer timer = null;
            XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
            new System.Threading.Timer((_) =>
            {
                using (var writer = XmlWriter.Create(_folderDestination, settings))
                {
                    //                Task.Delay(15000).ContinueWith(_ => doc.Save(writer));                
                    doc.Save(writer);
                }
            }).Change(15000, -1);

        }

Everytime the method printXML is called it would write the doc to the _folderDestination after a period of 15secs. This is what I want to achieve. But the above code seems to be leaking memory and the memory never returns back. So if someone could help to optimize it, it would be great.

System.Threading.Timer implements IDisposable.

Wrap it inside a using statement to make sure it gets Disposed properly.

If the purpose of the timer is to delay execution, an alternative way can to use a new Thread and do Thread.Sleep.

    public void printXML(XmlDocument doc)
    {
        var thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(DelayPrint));
        thread.Start(doc);
    }

    void DelayPrint(object param)
    {
        System.Threading.Thread.Sleep(15000);              
        XmlDocument doc = param as XmlDocument;
        // Do Work
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM