1

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
Uriel Katz
  • 319
  • 1
  • 8
  • 21

1 Answers1

2

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • The confusion rose from watching a video on threads with examples on a console application. I guess now the question is why is there foreground and background threads in VB.Net form applications if in the end the, as long as open, the application will execute the thread either way. The only thing I can think of is if doing some sort of function that needs to be completed whether the user closes the application or not, like an update. – Uriel Katz Jul 22 '13 at 06:20
  • @Uriel Console applications work very differently than Windows applications. In a Windows application (WinForms or WPF, doesn't matter), the "foreground" thread is the one that displays and manages the user interface and runs the message loop]. In fact, it's the *only* thread on which you can interact with the UI. You have to jump through hoops (e.g. the `Control.Invoke` method) to do that from a background thread. Background threads *will not* run when the application closes (i.e. the foreground thread exits). – Cody Gray - on strike Jul 22 '13 at 06:22