Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>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.</p> <p>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 <a href="https://stackoverflow.com/questions/4269800/c-webbrowser-control-in-a-new-thread/4271581#4271581">this answer</a> shows you how to do that.</p> <p>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 <em>that</em> code on a separate thread.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload