我为客户建立了一个群发电子邮件的网站,需要一次性发送80,000封电子邮件。它基本上为发送创建了一个新的线程,以便可以将控制权交回UI(以便可以加载反馈页面),然后为每个公司创建一个新的线程,以便向其收件人发送电子邮件。使用以下代码将所有电子邮件排队等待:
// Loop through the companies and send their mail to the specified recipients
// while creating a new thread for each company
// A new thread is started so that the feedback page can load
SendingThread = Task.Factory.StartNew(() =>
{
// This is a thread safe for loop
Parallel.ForEach<CompanyEntity>(companies, company =>
{
// Start a new thread for each company send
Task.Factory.StartNew(() =>
{
// Get the recipients for this company
var companyRecipients = GetSubscribersForCompany(company.Id, recipients);
// Send the newsletter to the company recipients
var success = SendNewsletterForCompany(newsletter, company, companyRecipients, language,
version, company.AdvertCollectionViaNewsletterCompanyAdvertLink, newsletter.NewsletterType, email);
// Add the status update so the front end can view a list of updated conpany statuses
if (success)
AddStatusUpdate(company.CompanyTitle + " has completed processing.");
// Starts sending the emails if the engine hasn't already been started
SendEngine.Start(CurrentSmtpClient, this);
}).ContinueWith(antecendent => EndCompaniesSendUpdate(companiesToProcess, companiesProcessed), TaskContinuationOptions.OnlyOnRanToCompletion);
});
}, new CancellationToken(), TaskCreationOptions.LongRunning, TaskScheduler.Default);
当电子邮件被排队时,发送引擎会接管并从队列中拉取电子邮件,然后使用新的Parallel类发送它们:
Action action = () =>
{
MailMessage message;
while (queue.TryDequeue(out message))
{
SendMessage(sendingServer, message, factory);
}
};
// Start 5 concurrent actions to send the messages in parallel.
Parallel.Invoke(action, action, action, action, action);
所有这些功能都很好,可以在大约10分钟内发送40,000封新闻通讯。唯一的问题是服务器上的RAM和CPU在这10分钟内被100%消耗。这会影响其他站点,因为它们无法访问。
有没有办法限制发送应用程序的资源使用,无论是在IIS 7.5中还是通过更改上面的代码?