Thread-safe call to a webbrowser control

G

Guest

Please, can someone please tell us how to call a webbrowser control
(navigate2 or navigate) from a worker thread safely?

I have stepped through tutorials on the web about delegated calls and invoke
methods but they don't make much sense to me... and all of them seemed overly
done just to change a single control value.

Right now I am getting an error that says:
"Current thread must be set to single thread apartment (STA) mode before OLE
calls can be made. Ensure that your Main function has STAThreadAttribute
marked on it."
.... and I am hoping that if I call the control safely, I will eliminate this
problem. (my application GUI is running in STA and if I change my worker
thread to run in STA it has memory read/write errors all over the place).

Here is the slimmed down code I am executing:

// Form1.cs
private void ManageRetrieveJobAndPopulateData()
{
// reset all data fields
ResetAllDataFields();

LoadAndRetrieveJobs_th = new Thread(new
ThreadStart(RetrieveJobAndPopulateData));

LoadAndRetrieveJobs_th.Priority = ThreadPriority.Normal;
// set thread to NORMAL priority


//LoadAndRetrieveJobs_th.SetApartmentState(ApartmentState.STA); // causes
memory errors

LoadAndRetrieveJobs_th.Start();

return;
} // ManageRetrieveJobAndPopulateData()

....

//worker thread still located in Form1.cs ... can be called either threaded
or non-threaded.

private void RetrieveJobAndPopulateData()
{
....
webBrowser1.Visible = true;
webBrowser1.Navigate("http://www..... /myTest.pdf"); // this is
bad, right?
// the above line causes the mentioned error so I think that we
need to call navigate safely
...
} // end RetrieveJobAndPopulateData ()

Can anyone help us? We are spending so much time on this and our software
release date is comming up quickly ... We can't figure it out.

Any help and suggestions are greatly appreciated.

Thanks,

Rob K
 
A

Andy

They might seem "overly" done, but that's what you need to do to access
controls in a thread safe manner. The Invoke will recall the same
method, but on the correct thread. Therefor you need to create Set
methods and define delegates for them so that Invoke can recall your
set function on the proper thread.
 
G

Guest

Thank you for replying Andy. I am going to take another crack at it again...
I will probably build a small test app first and see if I can get the basic
hang on whats going on.

Will let you know how it goes...

Rob K
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top