我尝试使用Threading.ThreadPool
发送电子邮件时遇到一种奇怪的行为。
这已经工作了一年多了,但最近它声称要间歇性地发送没有内容的电子邮件。收件人和主题都很好,但是,电子邮件的其余部分是空白的。没有任何改变代码的方式(除了Windows运行的服务器的更新)。
这是我正在使用的代码 - 是否有人建议我如何缩小问题发生的位置?将电子邮件重新发送给声称收到空白电子邮件的人后,他们就可以了 - 它使用与发送的第一个完全相同的代码。
子级生成电子邮件:
Public Sub EmailConfirmation(email As String,
firstname As String,
details As String)
Try
Dim embody As String = GlobalHelper.emailBody
'static class which loads the email text at application load for use later.
'This is a point of concern because it's obviously where the embody text is
'is loaded, but the issue is intermittent and if there was a failure here surely
'it would be caught by the 'try...catch' and a log of the error created (which has
'never happened). I also ran an experiment for a while where if this string was
'empty then create a log entry. After receiving a complaint of a blank email
'no error log was found.
embody = Replace(embody, "[FirstName]", firstname)
embody = Replace(embody, "[DATA]", details)
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("myemail@mydomain.com", "My Display Name")
mail.To.Add(email)
mail.IsBodyHtml = True
'set the content
mail.Subject = "Email Subject!"
mail.Body = embody
AddEmailToThreadPool(mail)
Catch ex As Exception
'if there is an error it is logged here.
End Try
End Sub
添加到ThreadPool的Sub:
Private Sub AddEmailToThreadPool(email As MailMessage)
System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf sendEmail), email)
End Sub
发送电子邮件的Sub:
Private Sub sendEmail(stateinfo As Object)
Dim email As MailMessage = CType(stateinfo, MailMessage)
Try
'send the message
Dim smtp As New SmtpClient("mail.mydomain.com")
smtp.Send(email)
Catch ex As Exception
'error is logged here.
End Try
End Sub
答案 0 :(得分:1)
我是从MSDN MailMessage class
复制的此类型的任何公共静态(在Visual Basic中为Shared)成员都是线程安全的。不保证任何实例成员都是线程安全的。
答案 1 :(得分:0)
好吧,在修复了错误的文档类型声明后,我几乎一个月内没有发过空白电子邮件的投诉。虽然我不确定为什么,但我会假设这解决了这个问题。
感谢您的所有输入/帮助。