我目前有一个小程序,可以检查用户是否有互联网连接时加载。如果没有,则显示图片框,否则图片框被隐藏。这在加载时完全正常,但是如果用户在加载程序后断开互联网连接,则没有任何反应。
我如何在计划中添加计时器或循环?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Checkthread = New Thread(AddressOf Me.CheckConnection)
Checkthread.Start()
End Sub
Private Sub CheckConnection()
If internetConnection() = False Then
InternetStatus = False
Else
InternetStatus = True
End If
AccessPicture()
End Sub
Private Sub AccessPicture()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf AccessPicture))
Else
If InternetStatus = False Then
PicInternet.Show()
Else
PicInternet.Hide()
End If
End If
End Sub
Private Function internetConnection() As Boolean
Dim req As System.Net.WebRequest = System.Net.WebRequest.Create("http://www.google.co.uk/")
Dim resp As System.Net.WebResponse
Try
resp = req.GetResponse()
resp.close()
req = Nothing
Return True
Catch ex As Exception
req = Nothing
Return False
End Try
End Function
答案 0 :(得分:1)
使用可帮助您轻松使用计时器代码的库,可以让您的生活更轻松。我建议使用微软的Reactive Framework(NuGet“Rx-WinForms”)。
这是你的代码:
Private _subscription As IDisposable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_subscription = _
Observable _
.Interval(TimeSpan.FromSeconds(30.0)) _
.StartWith(-1) _
.Select(Function(x) internetConnection()) _
.ObserveOn(Me) _
.Subscribe(Sub(x)
If x Then
PicInternet.Show()
Else
PicInternet.Hide()
End If
End Sub)
End Sub
这将设置一个可立即触发的观察,然后每30秒触发一次internetConnection
,并将其值发送到UI线程,以便显示或隐藏图片。
哦,这是internetConnection
方法的更简洁版本。
Private Function internetConnection() As Boolean
Dim req = System.Net.WebRequest.Create("http://www.google.co.uk/")
Try
Using resp = req.GetResponse()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
就是这样。
当您完成并希望关闭表单后,请先致电_subscription.Dispose()
以关闭观察结果。