Memory leak when SmtpMail and MailMessage are used.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have the function which consists code below. Every 50 mails the memory of
application raises up 100k. Sometimes is more. Does someone know why and what
I have to do to solve this problem.

for(int emailNum = 0; emailNum < int.Parse(txtMailsAmount.Text); emailNum++)

{

MailMessage tmp = new MailMessage();

SmtpMail.SmtpServer = mail.SmtpServer;

tmp.BodyFormat = mail.BodyFormat;

tmp.Body = mail.Body;

tmp.Subject = mail.Subject;

tmp.From = mail.From;

tmp.To = mail.To;

tmp.Cc = mail.Cc;

SmtpMail.Send(tmp);


}
 
It's normal. It's because the objects used aren't collected by the
garbage collector until the memory is needed.
 
You can assist the Garbage Collector by adding

tmp = Nothing

at the end of the loop. However, you will still see some memory growth
until the GC runs.

Mike.
 
Michael D. Ober said:
You can assist the Garbage Collector by adding

tmp = Nothing

at the end of the loop. However, you will still see some memory growth
until the GC runs.

No, this is useless. As tmp is reassigned at every iteration (tmp = new
MailMessage()), setting it to null (Nothing in VB) at the end of the loop
won't have any impact on the GC, it will only slow down your program.

On the side, calling int.Parse at every iteration to compute the upper bound
of the loop is a bad idea. You should rewrite the loop as:

int messageCount = int.Parse(txtMailsAmount.Text);
for (int i = 0; i < messageCount; i++)
// loop body...
 
You should assign null to local reference variables when you know you're done
with it. In a loop where the loop is re-assigning a new reference to the
variable setting it to null IS pointless. At the end of the loop, if you
know you're done with tmp, assign null to it.

This allows the GC to collect the data sooner, if it can; rather than for
the variable to go out of scope. It's best to make sure the scope of the
variable is such that it goes out of scope as soon as possible, making
assigning null to it moot.
 
Back
Top