WebBrowser control: “Specified cast is not valid.”?

WebBrowser is a COM component under the hood. An apartment threaded one, COM takes care of calling its methods in a thread-safe way. Your Navigate() call works for that reason, it is actually executed on the UI thread.

What doesn't work is the DocumentText property, it is implemented in the . NET wrapper and they somewhat fumbled the code. It bombs when the COM interop support in the CLR notices that a thread in the MTA tries to access a property of a component that lives on an STA.

WebBrowser is a COM component under the hood. An apartment threaded one, COM takes care of calling its methods in a thread-safe way. Your Navigate() call works for that reason, it is actually executed on the UI thread.

What doesn't work is the DocumentText property, it is implemented in the . NET wrapper and they somewhat fumbled the code. It bombs when the COM interop support in the CLR notices that a thread in the MTA tries to access a property of a component that lives on an STA.

Your call to SetApartmentState() isn't correct. It is made on the wrong thread, the UI thread already is STA. Also the reason it doesn't bomb, you cannot change the apartment state of a thread after it is started.

You must call it on the Thread object you created. It still doesn't solve your problem, two STA threads are not compatible. Two basic ways to solve your problem.

The first one is that you create the WebBrowser object itself on a separate STA thread. The code in this answer shows you how to do that. The browser you create that way cannot also be visible on your form.

Which is the second way, marshal the call yourself with Control.Invoke(). Doing this is however pretty pointless, all of your code executes on the UI thread anyway, you get no concurrency. There is no free lunch here.

Running it on a thread only gives you headaches. If you need time to process the document text then run that code on a separate thread.

I am for getting the state of the browser, but for the task I'm doing it requires a separate thread to not hang the app. – Drake May 1 at 14:26.

You must post the code. I am not sure though! But, still check this link and its related content : WebBrowser document cast not valid.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions