收录日期:2020/06/02 20:10:52 时间:2009-08-07 15:22:15 标签:.net,memory,smtp,stream,dispose

it seem, after looking with reflector, that the sendasync(smtpclient) with the object token in the parameter of the function is byval

does it make sense to try to release the attachment in the callback function?

everywhere people(myself included) seem to do sendasync(mailmessage,mailmessage)

and in the callback(SendCompletedCallback) doing something like:

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()

but since the sendasync is byval, that should not dispose the original attachment, right?

in my case, attachment are memorystream

The callback method gets references to the original objects, not copies of them.

The default way of sending an arguments is by value. If the argument is a reference type (object), that means that a copy of the reference is sent to the method, not that a copy of the object is created and sent to the method. There is still only one object, but there are two reference to it.

You only need to send an argument by reference if you need to change the variable, the method can still access the object if you send the argument by value.

Example:

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

Calling the method:

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

The variable x will now point to a StringBuilder object containing "a1".
The variable y will be Nothing.
There is a StringBuilder object containing "b2" that you no longer have a reference to.