Click here to Skip to main content
15,883,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good morning

I have a vb.net program that launches another form.

This form uses the BackgroundWorker to build a PDF whilst a progess bar is shown on the form.

VB
Private Sub frm_BuildPDF_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    ProgressBar1.Minimum = 0
    ProgressBar1.Maximum = 1000
    ProgressBar1.Value = 999

    BackgroundWorker1.RunWorkerAsync()

End Sub


Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    InitiateBuild()
    Me.Close()
End Sub


The program falls over with the following message when it hits the Me.Close statement :

System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Cross-thread operation not valid: Control 'frm_BuildPDF' accessed from a thread other than the thread it was created on.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.SendMessage(Int32 msg, Int32 wparam, Int32 lparam)
at System.Windows.Forms.Form.Close()
at PurchaseOrder.frm_BuildPDF.BackgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in C:\Users\Darrelld\Documents\Source Code\Power Systems\PurchaseOrder\PurchaseOrder\frm_BuildPDF.vb:line 45
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:

I have never used the BackgroundWorker before and all the reading I have done is not making much sense or seems over complicated.

All I am trying to achieve is show the user that the program is busy.
When the form is complete it must simply close.

Could any please advise how I close the form.
Note that there is no interaction required with the user.

Thanks everyone
Posted
Comments
Darrell de Wet 24-Oct-14 6:15am    
As always, your assistance is much appreciated.

1 solution

You cannot access controls or any other UI components, including forms from any thread except the one they were created on: the UI thread.

If you want to access controls in a BackgroundWorker, you have to Invoke them: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke(v=vs.110).aspx[^]
This "moves the code" onto the correct thread and continues execution from there. Do note that if the idea of the background worker is to free up the UI thread while doing a lot of updates, it won't have the desired effect: since the Invoke will move execution back onto the UI thread it may well slow things down!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900