问题描述
在延续我的这里问题,我创建了一个测试应用程序,使用线程池
线程发送电子邮件。这里的code我使用。
In continuation with my problem here, I created a test app that uses ThreadPool
threads to send emails. Here's the code I am using.
protected void btnSend_Click(object sender, EventArgs e)
{
EmailInfo em = new EmailInfo { Body = "Test", FromEmail = "[email protected]", Subject = "Test Email", To = "[email protected]" };
//txtNumEmails is a textbox where I can enter number of emails to send
for (int i = 0; i < Convert.ToInt32(this.txtNumEmails.Text); i++)
{
bool bResult = ThreadPool.QueueUserWorkItem(new WaitCallback(EmailNow), em);
}
}
public void EmailNow(object emailInfo) // Email Info object
{
EmailInfo em = emailInfo as EmailInfo;
SmtpClient client = new SmtpClient("localhost");
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = @"C:\temp\testemails\";
MailMessage m = new MailMessage();
m.To.Add(new MailAddress(em.To));
m.Body = em.Body;
m.IsBodyHtml = false;
m.From = new MailAddress(em.FromEmail);
m.Subject = em.Subject;
client.Send(m);
}
有关更小的数字(10K,50K),他们的工作很好,但是一旦我的数目增至20万(这是我的目标),我得到这个异常:
For smaller numbers (10k, 50k) they work great, but once I increase the number to 200k (which is my target), I got this exception:
这创造了约186K的电子邮件才抛出此异常。
It created about 186k emails before it threw this exception.
我假定这是不是导致异常由于缺乏磁盘空间(因为我存储所有的电子邮件在本地 C:\ TEMP \ testemails
,而是因为它较低的RAM(?)所建议的一个此用户,我用旗语给他们限制在10K,但仍跑在同一个问题,这里的$ C $下一个信号量。
I am assuming this is not the exception caused due to lack of disk space (since i am storing all the emails locally in C:\temp\testemails
but because it was low in RAM(?). As suggested by a this user, I used semaphores to limit them to 10k, but still ran in to the same issue. Here's the code for the one with semaphores.
protected void Button1_Click(object sender, EventArgs e)
{
EmailInfo em = new EmailInfo { Body = "Test", FromEmail = "[email protected]", Subject = "Test Email", To = "[email protected]" };
var semaphore = new SemaphoreSlim(10000, 10000);
for (int i = 0; i < Convert.ToInt32(this.txtNumEmails.Text); i++)
{
semaphore.Wait();
bool bResult = ThreadPool.QueueUserWorkItem( (state) => {
try
{
EmailNow(em);
}
catch (Exception)
{
throw;
}
finally
{
semaphore.Release();
}
}, null);
}
}
这一次引发了异常的好,但我看到所有200K的电子邮件的文件夹中。我肯定可以使用试捕
并正常退出,如果发生此异常,但如何将我的发生在首位prevent这一点。
This one threw an exception as well but I see all 200k emails in the folder. I can definitely use try catch
and gracefully exit if this exception occurs, but how would I prevent this from happening in the first place.
推荐答案
尝试减少10000至1000的SemaphoreSlim构造。
Try reducing the 10000 to 1000 for the SemaphoreSlim constructor.
这篇关于线程池和内存(BTStackServer)异常 - .NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!