带有AlternateViews的.NET SMTP SendAsync会抛出已处置的异常

时间:2009-04-22 18:53:30

标签: .net vb.net smtp sendasync alternateview

我正在尝试异步发送电子邮件,只要没有附加到电子邮件的AlternateView,它就可以正常工作。当有备用视图时,我收到以下错误:

Cannot access a disposed object. Object name: 'System.Net.Mail.AlternateView'
System.Net.Mail.SmtpException: Failure sending mail. ---> System.ObjectDisposedException: Cannot access a disposed object.

Object name: 'System.Net.Mail.AlternateView'.
   at System.Net.Mail.AlternateView.get_LinkedResources()
   at System.Net.Mail.MailMessage.SetContent()
   at System.Net.Mail.MailMessage.BeginSend(BaseWriter writer, Boolean sendEnvelope, AsyncCallback callback, Object state)
   at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)

以下是一些示例代码:

Dim msg As New System.Net.Mail.MailMessage
msg.From = New System.Net.Mail.MailAddress("me@example.com", "My Name")
msg.Subject = "email subject goes here"

'add the message bodies to the mail message
Dim hAV As System.Net.Mail.AlternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(textBody.ToString, Nothing, "text/plain")
hAV.TransferEncoding = Net.Mime.TransferEncoding.QuotedPrintable
msg.AlternateViews.Add(hAV)

Dim tAV As System.Net.Mail.AlternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(htmlBody.ToString, Nothing, "text/html")
tAV.TransferEncoding = Net.Mime.TransferEncoding.QuotedPrintable
msg.AlternateViews.Add(tAV)

Dim userState As Object = msg
Dim smtp As New System.Net.Mail.SmtpClient("emailServer")

'wire up the event for when the Async send is completed
 AddHandler smtp.SendCompleted, AddressOf SmtpClient_OnCompleted

 Try
     smtp.SendAsync(msg, userState)
 Catch '.... perform exception handling, etc...
 End Try

回调.....

 Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
    If e.Cancelled Then
      'Log the cancelled error
    End If
    If Not IsNothing(e.Error) Then
        'Log a real error....
        ' this is where the error is getting picked up
    End If

    'dispose the message
    Dim msg As System.Net.Mail.MailMessage = DirectCast(e.UserState, System.Net.Mail.MailMessage)
    msg.Dispose()

End Sub

3 个答案:

答案 0 :(得分:2)

这不起作用的原因是因为在SendAsync()方法完成时调用了OnCompleted处理程序,但这似乎是在SmtpClient完成通过网络物理发送电子邮件之前(这只会发生在网络上)虽然交付,文件传递基本上与SendAsync())同步。

这几乎就像是SmtpClient中的一个错误,因为只有在真正发送消息时才应该调用OnCompleted。

答案 1 :(得分:0)

我有一个非常类似的问题。相同的错误消息,但代码结构略有不同。在我的情况下,我在main函数中处理mailmessage对象。当OnCompleted事件运行时,该对象已经消失。

在SendAsync之后查看您的代码,看看您是否正在释放mailmessage对象。例如,如果您在using语句中创建它,那么它将在异步事件运行之前被释放。

答案 2 :(得分:0)

如果你想在回调中访问它们,你应该把你的dims放在班级。

private msg As System.Net.Mail.MailMessage
private hAV As System.Net.Mail.AlternateView 

private sub yoursub
  msg = new System.Net.Mail.MailMessage(..
  hAV = new ...
end sub

我的猜测是AlternateViews.Add只是添加了一个hAV的引用,msg对象需要处理,而hAV是由GC自动处理的。

干杯