Is it safe to use a Using block for an asynchronous object? If the block is exited before async task is complete, will the object be disposed too soon? Will it be disposed properly when the task completes?
This code works, but I don’t know whether it’s abusing my memory.
For i = 1 To nPings
Thread.Sleep(10)
Using pPing As New System.Net.NetworkInformation.Ping
AddHandler pPing.PingCompleted, AddressOf pingHandler
pPing.SendAsync(ip, timeout)
End Using
Next i
Yes. As soon as the
End Usingline completes, thePingobject will be disposed.In your example, the
Pingobject will always be disposed of. However, this may or may not happen after the async code completes as that behavior, the way you’ve coded it, is undetermined.To make this behavior more deterministic, dispose of the Ping object inside your
pingHandlercode, such that:Also, if you inspect the code inside the
Ping.Dispose(), you’ll see that it closes various EventHandles. This may not cause an exception if thePingobject is disposed before the async completes, but it certainly puts thePingobject in an unstable state. You might find events not firing or the async complete handler code not being called or other subtle things happening.