I changed target framework from 3.5 to 4.0, no other changes. A simple ping which worked with 3.5, now with 4.0 the result gives Canceled=True. Any ideas what may cause this?
Public Sub StartInternetConnectionCheckEvery(ByVal seconds As Integer)
Dim timer As New Timer()
timer.Interval = seconds * 1000
AddHandler timer.Tick, AddressOf CheckIsConnectedToInternet
timer.Start()
End Sub
Private Sub CheckIsConnectedToInternetByTimer(ByVal sender As Object, ByVal e As System.EventArgs)
CheckIsConnectedToInternet()
End Sub
Public Sub CheckIsConnectedToInternet()
Using ping As New System.Net.NetworkInformation.Ping()
Dim address As String = "www.google.com"
ping.SendAsync(address, Nothing)
AddHandler ping.PingCompleted, AddressOf OnPingResult
End Using
End Sub
Private Sub OnPingResult(ByVal sender As Object, ByVal e As PingCompletedEventArgs)
If e.Cancelled Then
Trace.WriteLine("InternetHelper: Ping Cancelled")
Return
End If
IsConnectedToInternet = (e.Reply.Status = IPStatus.Success)
RaiseEvent InternetPingResult(IsConnectedToInternet)
End Sub
Yes, this is not going to work well. You are disposing the ping object before the asynchronous send can complete. You got away with it before because the Ping class didn’t implement the Dispose() method properly. That got fixed in .NET 4, feedback report is here.
The fix is simple, remove Using. Disposing it properly is not so easy when you use it asynchronously. Try it in the event or don’t bother.
Otherwise a nice demonstration how framework bug fixes can break working code 🙂