BackgroundWorker IP Monitor

Updated Reverend Jim 1 Tallied Votes 2K Views Share

The code in this snippet (and attached project zip) demonstrates how to use a background worker thread to monitor a network address (name or IP). It shows how to start and stop the thread and how to update controls in the main thread using delegates. It should be simple to use this code as a template for creating background threads for other tasks.

A couple of quick notes:

You may wonder why I have tab characters padding out my comments. It becomes more obvious when you set the comments to display with black foreground and light grey (or silver) background. When you do this it becomes a little prettier to look at. I prefer shaded comments because it more easily distinguishes code from comments, and makes it more obvious when code is commented out.

<edit>It looks like trailing blanks/tabs are automatically removed</edit>

The attached file is named as "yyyy-mm-dd hh-mm archive.zip". I don't use a CMS. When I get to a checkpoint I have a script that archives a folder. It prefixes the project folder name with the current date and time.

'                                                                               
'  Name:                                                                        
'                                                                               
'    BGPing                                                                     
'                                                                               
'  Description:                                                                 
'                                                                               
'    Sample code for starting and stopping a background thread. Also shows how  
'    to update foreground controls from background threads using delegates.     
'                                                                               
'  Audit:                                                                       
'                                                                               
'    2012-11-18  Reverend Jim - original code                                   
'                                                                               

Public Class Form1

    'Background threads cannot write to controls in other threads. In order to  
    'update the status label you have to access it through a delegate. You'll   
    'see how this works in the UpdateStatus Sub.                                

    Private Delegate Sub dlgUpdateStatus(text As String)

    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        'If the background thread is active, kill it. We already have the code  
        'in the button click handler so let's just use that.                    

        If btnStart.Text = "Stop" Then
            btnStart.PerformClick()
        End If

    End Sub

    Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click

        'We'll start and stop the background worker using one button. We'll     
        'toggle the button text as we change states between running to stopped. 

        Dim btn As Button = sender

        If btn.Text = "Start" Then      'start the background thread
            btn.Text = "Stop"
            bgwPing.RunWorkerAsync()
        Else
            btn.Text = "Start"
            bgwPing.CancelAsync()       'tell the background thread to stop itself
        End If

    End Sub

    Private Sub UpdateStatus(text As String)

        'The InvokeRequired method returns True if the thread that calls it     
        'is running from a different thread. In that case we create a delegate  
        'to do the update of the control's text otherwise we can update the     
        'text directly.                                                         

        If lblStatus.InvokeRequired Then
            Dim dlg As New dlgUpdateStatus(AddressOf UpdateStatus)
            Me.Invoke(dlg, text)
        Else
            lblStatus.Text = TimeOfDay & " " & txtAddress.Text & " is " & text
        End If

    End Sub

    Private Sub bgwPing_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwPing.DoWork

        Do

            'If the foreground thread requested a cancellation then set the     
            'appropriate flag and exit the loop.                                

            If bgwPing.CancellationPending Then
                e.Cancel = True
                Exit Do
            End If

            'do the ping and update the status label

            If My.Computer.Network.Ping(txtAddress.Text) Then
                UpdateStatus("Responding")
            Else
                UpdateStatus("Not Responding")
            End If

            'suspend for five seconds before the next ping

            System.Threading.Thread.Sleep(5000)

        Loop

    End Sub

End Class
Pgmer 50 Master Poster Featured Poster

Good code to understand the concept of delegates for those who never used in real time.

Reverend Jim 4,968 Hi, I'm Jim, one of DaniWeb's moderators. Moderator Featured Poster

Thanks. It seems a lot of examples of code in books are like this.

john.knapp commented: LOL +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.