The following lines cause a memory leak:

MailMessage msg = new MailMessage(mail, mail, "?", ""); msg.Attachments.Add(new Attachment(filePath, MediaTypeNames.Text.Plain)); var client = new SmtpClient("smtp.mail.ru", 25); client.Credentials = new NetworkCredential(mail, "password"); client.EnableSsl = true; client.Send(msg); client.Dispose(); msg.Attachments.Dispose(); msg.Dispose(); 

Is it possible to solve this problem? It seems all dispose caused.

    2 answers 2

    Dispose does not free memory. It simply asks the class to destroy unmanaged resources (all sorts of handles there and so on, that client is used there).

    Memory in .net is freed non-deterministic by the garbage collector. Flows - this is when memory consumption grows with time, with each call of your code. And for you - it is simply not released instantly, and so it was conceived.

    • This part of the code is called once, but the task manager constantly increases the consumption of RAM by the program - KnowNamed
    • @KnowNamed then you should take a memory profiler and look for a real leak - PashaPash

    Instead of explicitly calling Dispose() it is better to use using

     using(var client = new SmtpClient("smtp.mail.ru", 25)) using(var msg = new MailMessage(mail, mail, "?", "")) { msg.Attachments.Add(new Attachment(filePath, MediaTypeNames.Text.Plain)); client.Credentials = new NetworkCredential(mail, "password"); client.EnableSsl = true; client.Send(msg); } 

    Destroy Attachment does not make sense, it will be destroyed when a message is destroyed.