【问题标题】:ThreadPool and Memory (BTStackServer) exception - .NET线程池和内存 (BTStackServer) 异常 - .NET
【发布时间】:2012-03-14 06:56:04
【问题描述】:

继续我的problem here,我创建了一个使用ThreadPool 线程发送电子邮件的测试应用程序。这是我正在使用的代码。

        protected void btnSend_Click(object sender, EventArgs e)
        {
            EmailInfo em = new EmailInfo { Body = "Test", FromEmail = "test@test.com", Subject = "Test Email", To = "test@test.com" };
//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),它们工作得很好,但是一旦我将数字增加到 200k(这是我的目标),我就会遇到这个异常:

在引发此异常之前,它创建了大约 186k 封电子邮件。

我假设这不是由于磁盘空间不足引起的异常(因为我将所有电子邮件本地存储在 C:\temp\testemails 但因为它的 RAM 不足(?)。正如 this user 所建议的那样,我使用信号量将它们限制为 10k,但仍然遇到同样的问题。这是带有信号量的代码。

    protected void Button1_Click(object sender, EventArgs e)
    {
        EmailInfo em = new EmailInfo { Body = "Test", FromEmail = "test@test.com", Subject = "Test Email", To = "test@test.com" };
        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 电子邮件。如果发生此异常,我绝对可以使用try catch 并优雅地退出,但是我如何首先防止这种情况发生。

【问题讨论】:

  • 哇...这不是普通的错误。像这样的致命崩溃通常是由 CLR 中的错​​误、行为不端的非托管代码、不正确地使用非托管代码等引起的。我同意 Deepansh 的建议并尝试处理该 SmtpClient 对象。除此之外,您需要获取崩溃报告并检查堆栈跟踪以寻找线索。

标签: asp.net .net multithreading .net-4.0 threadpool


【解决方案1】:

尝试通过使用块封装或显式调用 dispose() 来处理 SmtpClient 对象。

【讨论】:

    【解决方案2】:

    尝试将 SemaphoreSlim 构造函数的 10000 减少到 1000。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 2021-04-11
      相关资源
      最近更新 更多