迭代不按预期工作

时间:2012-01-18 21:12:03

标签: vb.net

我正在使用DO交互来循环我用来测试互联网连接的功能。代码工作正常,除了当其中一个测试满足时循环停止。我想在程序运行时继续在后台运行。我怎样才能让它发挥作用?

Private Sub checkInternet()

    Dim InetChecker As Boolean
    InetChecker = CheckForInternetConnection()
    Do While LabelCount.Text <> ""
        Thread.Sleep(10)
        If InetChecker = True Then
            Dim image = My.Resources.greenbar
            PictureBox4.Image = image

        Else
            Thread.Sleep(10)
            Dim image = My.Resources.redbar
            PictureBox4.Image = image
            'NoInetConnError.Show()
        End If
    Loop
End Sub

非常感谢您的协助,谢谢。

3 个答案:

答案 0 :(得分:2)

在表单上放置BackgroundWorker(您可以在工具箱的“组件”部分找到它。)

在“属性”窗口中,为您的BackgroundWorker设置WorkerReportsProgressTrue

将以下代码插入表单

Private connected As Boolean

Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
 Handles BackgroundWorker1.DoWork
    While True
        Dim online = CheckForInternetConnection()
        If online <> connected Then
            connected = online
            BackgroundWorker1.ReportProgress(CInt(online))
        End If
        Thread.Sleep(500)
    End While
End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
 Handles BackgroundWorker1.ProgressChanged
    Dim online As Boolean = CBool(e.ProgressPercentage)
    If online Then
        PictureBox4.Image = My.Resources.greenbar
    Else
        PictureBox4.Image = My.Resources.redbar
    End If
End Sub

Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
 Handles MyBase.Load
    ' Start the background worker
    BackgroundWorker1.RunWorkerAsync()
End Sub

请注意,Sub BackgroundWorker1_DoWork在单独的线程上运行,并且在运行时不会冻结您的表单。

答案 1 :(得分:1)

最好在Timer而不是循环中执行此类操作。

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
  If CheckForInternetConnection Then
    PictureBox4.Image = My.Resources.greenbar
  Else
    PictureBox4.Image = My.Resources.redbar
  End If
End Sub

答案 2 :(得分:0)

如果您可以访问.Net framework 3+,那么您可以使用DispatcherTimer类,它基本上创建一个间隔(设置为您需要的任何长度),您可以处理它的tick事件。引发tick事件时,您可以进行互联网连接检查。

根据您的情况修改MSDN示例,您可以执行以下操作:

'  DispatcherTimer setup
dispatcherTimer = New Threading.DispatcherTimer()
AddHandler dispatcherTimer.Tick, AddressOf dispatcherTimer_Tick
dispatcherTimer.Interval = New TimeSpan(0,0,1) ' Or however long you want
dispatcherTimer.Start()

Private Sub dispatcherTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
    ' Checks to see whether an internet connection is still available etc
    checkInternet()

    ' Forcing the CommandManager to raise the RequerySuggested event
    CommandManager.InvalidateRequerySuggested()
End Sub