none
BackgroundWorker in "Load Form" is not performing its function RRS feed

  • Question

  • the  MainFrm_Load of my project contains many code and it take much longer than usual to run 

    so i placed part of the code in a BackgroundWorker

    as you see from the following sample

     
    Dim c As New ClsSmWrk     
       If Not c.BWFrsPrtOfLd.IsBusy = True Then            c.BWFrsPrtOfLd.RunWorkerAsync()    
        End If
    
    
    
    Public Class ClsSmWrk
        Public WithEvents BWFrsPrtOfLd As New BackgroundWorker
    
     Private Sub BWFrsPrtOfLd_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWFrsPrtOfLd.DoWork
            Call MainFrm.LoadFncP()
        End Sub

    the function of the code is to load data into all fields and controls

    the problem is that

    if the code runs from a BackgroundWorker, and it not load any Data in Any field

    but if i run the same code from a control button it works perfectly

    Looking Forward to a quick solution


    Monday, October 28, 2019 8:54 PM

Answers

  • Your problem is that it will not update the form because the second thread doesn't really have access to it. You can try updating the form in progressbar change, but that can fail too if there is a lot to do in there. I'm guessing some type of garbage-collection/recycling.
    • Marked as answer by MosheS Singer Tuesday, October 29, 2019 7:52 PM
    Monday, October 28, 2019 10:50 PM

All replies

  • Hi

    Quick solution: use Invoke to avoid cross thread issues.Was there an exception? You say things like 'gets stuck'and 'it does not accomplish anything' neither of which are recognised errors. Did you get an exception anywhere, or, possibly, you have empty Try ... Catch blocks to avoid these pesky errors.


    Regards Les, Livingston, Scotland


    • Edited by leshay Monday, October 28, 2019 9:14 PM
    Monday, October 28, 2019 9:13 PM
  • Pleas re-read my problem to get a better understanding

    thanks

     
    Monday, October 28, 2019 9:29 PM
  • I am sorry, but the problem is difficult to understand.


    Sam Hobbs
    SimpleSamples.Info

    Monday, October 28, 2019 10:10 PM
  • Pleas re-read my problem to get a better understanding

    thanks

     

    Hi

    Please re-read my answer to get a better solution.


    Regards Les, Livingston, Scotland

    Monday, October 28, 2019 10:18 PM
  • Your problem is that it will not update the form because the second thread doesn't really have access to it. You can try updating the form in progressbar change, but that can fail too if there is a lot to do in there. I'm guessing some type of garbage-collection/recycling.
    • Marked as answer by MosheS Singer Tuesday, October 29, 2019 7:52 PM
    Monday, October 28, 2019 10:50 PM
  • Hi

    Here is a simple BGW example. Please note the comments regarding the updating of Label2.

    ' BLANK Form1
    ' Copy/Replce existing Form1 code
    ' with this code.
    
    Option Strict On
    Option Explicit On
    Imports System.ComponentModel
    
    Public Class Form1
    	Dim WithEvents bgw As New BackgroundWorker
    	Dim WithEvents Button1 As New Button
    	Dim Label1, label2 As New Label
    	Dim PendingClose As Boolean = False
    	Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    		If bgw.IsBusy Then
    			bgw.CancelAsync()
    			PendingClose = True
    			e.Cancel = True
    		End If
    	End Sub
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		With Label1
    			.Text = "Click Start"
    			.Location = New Point(10, 40)
    		End With
    		With label2
    			.Text = "Label2"
    			.Location = New Point(10, 70)
    		End With
    		With Button1
    			.Text = "Start"
    			.AutoSize = True
    			.Location = New Point(10, 10)
    		End With
    		With bgw
    			.WorkerReportsProgress = True
    			.WorkerSupportsCancellation = True
    		End With
    
    		Controls.AddRange({Button1, Label1, label2})
    	End Sub
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Select Case Button1.Text
    			Case "Start"
    				bgw.RunWorkerAsync()
    				Button1.Text = "Stop"
    			Case Else
    				bgw.CancelAsync()
    				Button1.Text = "Start"
    		End Select
    	End Sub
    	Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
    
    		' ============================
    		' This block is ONLY for this
    		' example and would be
    		' replaced with your file
    		' handling code with appropriate
    		' care taken for Cancelling and
    		' Reporting.
    		' File Operations such as
    		' IO.File.Move(sourceFileName:=, destFileName:=)
    		' IO.File.Copy(sourceFileName:=, destFileName:=)
    		' IO.File.Delete(path:=)
    		' IO.File.Exists(path:=)
    
    		Dim i As Integer = 1
    		Dim R As New Random
    		Do
    			If bgw.CancellationPending Then
    				e.Cancel = True
    				Exit Do
    			End If
    
    			' Update a Label which is on the Main thread
    			' NOTE: a plain Label1.Text = "ABC" would
    			' not work as it would be a Cross-Thread
    			' issue!
    			Invoke(Sub() label2.Text = R.Next(999, 99999).ToString)
    
    			bgw.ReportProgress(i)
    			i += 1
    			' add artificial delay to 
    			' emulate work being done
    			Threading.Thread.Sleep(200)
    		Loop
    		' specifically using a never
    		' ending Loop to illustrate
    		' UI remaining responsive
    		' ============================
    
    	End Sub
    	Private Sub bgw_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles bgw.ProgressChanged
    		Label1.Text = "Completed " & e.ProgressPercentage.ToString & " Operations"
    	End Sub
    	Private Sub bgw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
    		Label1.Text = "Click Start"
    		If PendingClose Then Close()
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Monday, October 28, 2019 11:09 PM
  • Async is often misunderstood. Keep in mind that Async or back ground workers don't speed up anything. On the contrary, it slows down.

    As well you must prevent that the user takes action in the foreground, which can disturb the well handling of the returned result from the background.

    Looking at your code I think you did nothing to solve that. 

    This is never given in samples, because the foreground actions are mostly very special to the problem which has to be solved and mostly takes much more code than the task to be done. 


    Success
    Cor



    Tuesday, October 29, 2019 10:29 AM
  • Hello,

    Have you considered Iterator/Yield approach?


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, October 29, 2019 12:01 PM
    Moderator