I have written a C++ class that encapsulates a web browser (inspired by this). One of the class methods takes HTML code as a string and renders it in the browser. The browser's rendering is asynchronous, and in some situations it is necessary to wait until document loading is complete before proceeding. I am uncertain of whether I am doing this correctly.
What I do is open a new document, call IHTMLDocument2::put_onreadystatechange
(passing an instance of an EventSink
class that I implemented), and call IHTMLDocument2::write
to render the desired HTML. This is all done in the main thread.
The main thread then continues with other things. After a while, when the ready state changes, the browser calls EventSink::Invoke
. There, I call IHTMLDocument2::get_readyState
and check whether it equals complete
. This also happens in the main thread (called by COM via the client stub, if my understandung is correct).
The problem is that although I detect when document loading is complete, the main thread has been doing other things in the mean time, possibly accessing the HTML DOM. So I would like to wait for document completion immediately after calling IHTMLDocument2::write
. How does one achieve this? I can't set an event semaphore in the event sink and wait for it, because both pieces of code are executed by the main thread. So should I really be using a worker thread here? I'm somewhat confused about which thread would do what. E.g. the thread invoked by the COM client stub would set the event semaphore when loading is complete, but which thread is that - always the main thread, or the thread that created the COM object? Any help is appreciated.