问题
Sorry for my english
I've searched around, but did not get an answer to this question: I have a windows application project, using boost thread libraries. I want to post messages(or, invoke callbacks) from a worker's thread to the main UI thread. I studied the samples in boost::asio, all of them used in a blocked main thread, but my UI thread is working asynchronous.
Would you please help me? thanks a lot!
回答1:
Since the UI thread has its own message loop, you can't call in its context the blocking io_service::run()
function. What you can do is to interleave a polling UI-related method with io_service::poll_one()
:
// WARINING: untested code
MSG msg;
while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (io_service_.stopped())
io_service_.reset();
error_code ec;
io_service_.poll_one(ec);
}
Now, when you post functors to io_service_
, you actually post them to the main GUI thread.
(Certainly, if you use some GUI framework, you should use the appropriate framework method instead of PeekMessage
.)
回答2:
The UI thread is it a webkit similar kind of UI or plain windows forms, because if you are using webkit then u can handle it in a different way. OR Try using Delegates. OR finally if nothing works out, you can run a while loop checking an vector for any new input and add to the vector from the thread callback function.
I prefer if you could use delegate. (pointer function)
Here is a sample code for pointer function:
define a function like this:
typedef boost::function<void(std::string)> fnLog;
or if u want to go specifically for windows then
typedef void (__stdcall *fnLog)(char* val);
fnLog is the function with std::string parameter. then bind your function which is in UI thread to the pointer function
fnLog myPointerFunc = boost::bind( &UI::f1, _1);
then pass
myPointerFunc
as callback.
for more reference check on http://www.radmangames.com/programming/how-to-use-boost-function
来源:https://stackoverflow.com/questions/17311512/howto-post-messages-between-threads-with-boostasio