Question

I have a background worker control on a form.

In this form I have another form that shows a progress:

Private _fWait As frmWait

I am updating this form, change its label to tell the user what is currently going on.

When the background worker is finished, I want to close this form _fWait.

I am using

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

    'do the background worker stuff. I have not stated it here because it is not important

    _fWait.Close()

    _bDone = True

End Sub

But I am getting the error "Invalid cross-thread access: The access to the control frmWait occured from a diffent thread than the thread it was created by." on the line "_fWait.Close()".

Can somebody tell me what I did wrong?

Thank you!

Was it helpful?

Solution

When you call _fWait.Close() is has to be called on the UI thread whereas the BackgroundWorker1_DoWork handler will be running on a different thread which is why you are getting the error. There are two options for closing the form:

1) Continue to close the form on the DoWork handler but marshal the request onto the UI thread using something like the code below:

this.Invoke(() => _fWait.Close());

It's been a while since I've done VB, so you'll have to convert the C# code into VB...sorry.

2) Handle the RunWorkerCompleted event and close it there. If you BackgroundWorker was started on the UI thread, then the RunWorkerCompleted will also be called on the UI thread.

If I remember right the ProgressedChanged event will also be called on the UI assuming that the BackgroundWorker was created on the UI thread. If the BackgroundWorker is created another another thread, then the RunWorkerCompleted and ProgressChanged will also be called on a separate thread and you will have to marshal calls to the UI as described above in step 1.

OTHER TIPS

In simple programs, you can ignore cross-thread errors by adding this to your Form.Load method:

CheckForIllegalCrossThreadCalls = False

Note that it can cause problems when running multiple asynchronous threads that access shared data, so don't use it indiscriminately.


If multiple threads cause a shared routine to run, use SyncLock to prevent multiple simultaneous instances.

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