Verify internet connection in vb.net [duplicate]

别等时光非礼了梦想. 提交于 2020-05-16 05:53:25

问题


I wrote this in VB.NET:

Function Net() As Boolean
    Return My.Computer.Network.Ping("216.58.209.142")
End Function

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        If Net() = True Then
            InternetConnection.ForeColor = Color.Green
            InternetConnection.Text = "OK"
        ElseIf Net() = False Then
            InternetConnection.ForeColor = Color.White
            InternetConnection.BackColor = Color.Red
            InternetConnection.Text = "KO"
        End If
    Catch ex As Exception
        InternetConnection.Text = "KO"
    End Try
End Sub

How to check internet connection every minute? I tried using a BackgroundWorker but I don't know how to use it and my application crashed.


回答1:


One of the alternatives is to use Task.Delay

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    CheckConnection()
End Sub

Async Sub CheckConnection()
    Await Task.Delay(60000)
    Try
        If Net() = True Then
            InternetConnection.ForeColor = Color.Green
            InternetConnection.Text = "OK"
        ElseIf Net() = False Then
            InternetConnection.ForeColor = Color.White
            InternetConnection.BackColor = Color.Red
            InternetConnection.Text = "KO"
        End If
    Catch ex As Exception
        InternetConnection.Text = "KO"
    End Try
    CheckConnection()
End Sub


来源:https://stackoverflow.com/questions/46134507/verify-internet-connection-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!