【问题标题】:sendasync (smtpclient) when using the token is sent byval and not byref?sendasync(smtpclient)在使用令牌时发送byval而不是byref?
【发布时间】:2010-11-17 17:44:57
【问题描述】:

在查看反射器后,函数参数中带有对象令牌的 sendasync(smtpclient) 似乎是 byval

在回调函数中尝试释放附件有意义吗?

到处都有人(包括我自己)似乎在做 sendasync(mailmessage,mailmessage)

并在回调(SendCompletedCallback)中执行以下操作:

Dim mail As Net.Mail.MailMessage = CType(e.UserState, Net.Mail.MailMessage)

For i = (mail.Attachments.Count - 1) To 0 Step -1
  mail.Attachments(i).Dispose()
Next

mail.Dispose()

但是由于 sendasync 是 byval,所以不应该处理原始附件,对吧?

就我而言,附件是内存流

【问题讨论】:

    标签: .net memory smtp stream dispose


    【解决方案1】:

    回调方法获取对原始对象的引用,而不是它们的副本。

    发送参数的默认方式是按值。如果参数是引用类型(对象),这意味着将引用的副本发送到方法,而不是创建对象的副本并将其发送到方法。仍然只有一个对象,但有两个对它的引用。

    如果需要更改变量,只需通过引用发送参数,如果通过值发送参数,方法仍然可以访问对象。

    例子:

    Sub Test(ByVal x As StringBuilder, ByRef y As StringBuilder)
       ' accessing the objects
       x.Append("1")
       y.Append("2")
       ' remove the copy of the reference to x
       x = Nothing
       ' remove the reference to y
       y = Nothing
    End Sub
    

    调用方法:

    Dim x As New StringBuilder("a")
    Dim y As New StringBuilder("b")
    Test(x, y)
    

    变量 x 现在将指向包含 "a1"StringBuilder 对象。
    变量 y 将是 Nothing
    有一个 StringBuilder 对象包含您不再引用的 "b2"

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2010-10-08
      • 2012-01-21
      • 1970-01-01
      相关资源
      最近更新 更多