我们在发送大量电子邮件时遇到问题(大约60k~70k)。 我们通常在30k标记处获得Out of Memory异常。 我们循环遍历客户端列表,我们通过根据客户端传递参数来修改字符串,该客户端稍后加载到MailMessage对象的主体中。 当我们使用线程来加速进程时会发生此错误。我们在不使用线程时不会收到错误,但是这个过程大约需要9个小时,这是我们无法接受的。 我们可以做些什么来控制内存行为或任何可以通过整个列表而不会出现此错误的内容? 请参阅以下部分代码:
foreach (var candidate in z)
{
var mailer1 = new MailerProto();
string jobList = "";
foreach (var item in candidate)
{
string title = item.title;
jobList += "<a href='" + "https://mydomain/" + "job/" + title + "-" + item.jobId + "?emailId=" + item.accountId + "'>" + title + " </a><br class='br' />";
}
string[] args = new string[]
{
AppConfig.Url,
candidate.FirstOrDefault().firstName,
jobList,
candidate.FirstOrDefault().accountId.ToString()
};
tasks[taskCounter] = mailer1.SendEmail(
from: AppConfig.NoReplyMail,
to: candidate.FirstOrDefault().email,
subject: "We have found jobs just for you!",
htmlContent: content,
args: args,
skipSubscription: true
);
taskCounter += 1;
if (taskCounter == 5000)
{
Task.WhenAll(tasks);
tasks = new Task[5000];
taskCounter = 0;
GC.Collect();
//System.Threading.Thread.Sleep(500);
}
}
然后是SendMail函数的一部分
for (int i = 0; i < args.Length; i++)
{
htmlContent = htmlContent.Replace("{" + i + "}", args[i]);
}
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
MailMessage messageMail = new MailMessage();
messageMail.To.Add(to);
messageMail.From = new MailAddress(from, displayName);
messageMail.Subject = subject;
messageMail.IsBodyHtml = true;
messageMail.Body = htmlContent;
if (attachments != null)
{
foreach (var item in attachments)
{
messageMail.Attachments.Add(new Attachment(item.Value, item.Key));
}
}
smtpClient.SendCompleted += (s, e) =>
{
smtpClient.Dispose();
messageMail.Dispose();
};
await smtpClient.SendMailAsync(messageMail);
smtpClient.Dispose();
messageMail.Dispose();
}
catch (Exception e)
{
MailMessage messageMail = new MailMessage();
messageMail.To.Add("errors@mydomain");
messageMail.From = new System.Net.Mail.MailAddress(AppConfig.NoReplyMail);
messageMail.Subject = "Api Error";
messageMail.IsBodyHtml = true;
messageMail.Body = e.Message + "\n " + e.InnerException + "\n" + "to: " + to + "\n subject:" + subject + "\args: " + result;
using (var smtpClient = new SmtpClient())
{
smtpClient.Send(messageMail);
}
}
}
是的,我们知道我们正在使用&#34;使用&#34;和多个&#34; Dispose&#34;,但没有一个有任何影响。这只是我们测试的一部分。