2014-11-14 14 views
0

我試圖發送具有附件的異步電子郵件。這些附件是即時生成並保存到服務器的,因此我想在電子郵件發送後刪除它們。刪除MailMessage附件會導致網站掛起

下面的代碼發送郵件成功,但整個網站後來鎖定。我只能假設它不能刪除已附加到電子郵件中的生成文件,不會拋出錯誤,也不會發布日誌。我知道文件路徑是正確的,因爲正在使用相同的路徑將文件附加到電子郵件。注意我正在處理消息和附件對象。

在我的開發環境中一切正常,但不是在生產環境中。應該注意的是,該代碼正在從位於網站bin文件夾中的.dll執行。

ThreadStart starter = delegate { SendAsync(ref message, Attachments, Settings); }; 
Thread thread = new Thread(starter); 
thread.IsBackground = true; 
thread.Start(); 

private static void SendAsync(ref MailMessage Message, List<clsEmailAttachment> Attachments, clsSmtpSettings Settings) 
{ 
    try 
    { 
     SmtpClient smtp = new SmtpClient(); 
     smtp.Host = Settings.Host; 
     NetworkCredential Credential = new NetworkCredential(Settings.Username, Settings.Password, Settings.Domain); 
     smtp.UseDefaultCredentials = false; 
     smtp.Credentials = Credential; 
     smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
     smtp.Send(Message); 
    } 
    catch (Exception SendingEmailException) 
    { 
     Log.PostLog(null, 4007, SendingEmailException.Message); 
    } 
    finally 
    { 
     try 
     { 
      Message.Attachments.Dispose(); 
      Message.Dispose(); 
      foreach (clsEmailAttachment attachment in Attachments) 
      { 
       if (attachment.Delete == true) 
       { 
        try 
        { 
         File.Delete(attachment.Path); 
        } 
        catch { throw; } 
       } 
      } 
     } 
     catch (Exception DeletingAttachmentsException) 
     { 
      Log.PostLog(null, 4008, DeletingAttachmentsException.Message); 
     } 
    } 
} 
+0

您是否嘗試過調試它? 'foreach'循環中'attachment'的值是多少? – Ckrempp 2014-11-14 17:29:22

回答

0

經過多次試驗和錯誤,我已經解決了這個問題。事實證明這是Attachments集合中的一個多線程問題。被稱爲一個新的線程執行以下操作:

private static void SendAsync(ref MailMessage Message, List<clsEmailAttachment> Attachments, clsSmtpSettings Settings) 

Generic.List<type>一個線程集合。以下語句取自msdn:

.NET Framework 2.0中引入的集合類可在System.Collections.Generic命名空間中找到。這些包括列表,詞典等。與.NET Framework 1.0類相比,這些類提供了改進的類型安全性和性能。但是,.NET Framework 2.0集合類不提供任何線程同步;當多個線程同時添加或刪除項目時,用戶代碼必須提供所有同步。

看到這裏的Full article