Question

Researching I found out that Background Worker is a background thread, however when I run the following code Background Worker still runs until the end even when the main procedure is exited. Isn't this feature reserved to foreground threads?

Code:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Run background worker
        BackgroundWorker1.RunWorkerAsync()
        'Display exit message
        MsgBox("Main procedure exited")
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        'Wait 10 seconds
        Threading.Thread.Sleep(10000)
        'Modify some numbers
        Dim variable = 3
        variable -= 1
        'Display exit message
        MsgBox("Background thread " & variable & " exited")
    End Sub
End Class
Was it helpful?

Solution

The Form1_Load method is not the "main procedure", so the message box that you're displaying at the end of it is actually a lie. That's just an event handler method for the Form.Load event, raised when your form is being displayed for the first time.

The "main procedure" is named Main and is defined in a separate file (actually, in VB.NET, it's automatically generated by the compiler and not even visible to you by default). You can find more information on the Main method in Microsoft's VB Programming Guide.

The Main method is still running as long as your program is still running. After the Form1_Load event handler method finishes, Form1 is still on the screen, so clearly your program hasn't closed yet. And since your program's main thread is still running, the BackgroundWorker object's background thread is still running, asynchronously, just like you told it to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top