Search code examples
.netvb.netsqlitebackgroundworkervb.net-2010

Can I use backgroundWorker after calling hide method in VB.NET


I have a simple question about Background worker. I have never used it so I have no Idea about how it works. I am using VB.NET express 2010. All I want to do a database monitoring in a form's backgroundWorker.

Here are few things I am trying to achieve.

  1. Monitoring SQLite DB file with select statement.
  2. Extracting Data from DB and put them into variables.
  3. Compare values with certain conditions and if something matches, pass values to another form and call it.
  4. Keep on monitoring.
  5. I want background worker to do this when form's form.hide() method is called.

Please give your valuable response and if i't not the correct way, please suggest another one so.


Solution

  • Hiding the form will not stop the background worker - in fact closing the form will not stop it - the form will wait for the background worker isBusy property to report false before continuing.


    Update in Response to new comment

    You'd probably be best using a timer and offloading the other work to a new thread, see example below. If the operation hasn't completed then the If _worker is nothing will stop the operation from being restarted. Be sure to set _worker = nothing at the end of your process for this to work though.

    Also I've just typed this up quickly, it may not work out of the box but should give you a starting point.

    Imports System.Threading
    
    Public Class Form1
    
        Dim _worker As Thread
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Timer1.Interval = 10000
            'interval in milliseconds so 1000ms = 1 second / above 10000 = 10 seconds
    
            Timer1.Enabled = True
            Timer1.Start()
    
        End Sub
    
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            StartWorkerThread()
        End Sub
    
        Private Sub StartWorkerThread()
    
            If _worker Is Nothing Then
                _worker = New Thread(AddressOf myWorker)
                _worker.Start()
    
    
            End If
    
        End Sub
    
        Private Sub myWorker()
            'do your work here...use an event or a delate to fire another sub/function on the main thread if required
    
                'when finished
                _worker = nothing
                'Important! This will allow the operation to be started again on the timer tick
            End Sub
    
        End Class