简体   繁体   English

主线程的C ++调用方法

[英]C++ call method from the main Thread

In one of my class i'm launching a thread using the following method: 在我的一堂课中,我正在使用以下方法启动线程:

HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &myThread, NULL, 0, &threadID );

And from this thread I would like to call a method that has to be called from the main thread (the method is interacting with the UI) but I really don't know how to do it since the main thread can't wait until "myThread" notifies it. 从这个线程中,我想调用一个必须从主线程中调用的方法(该方法正在与UI交互),但是我真的不知道该怎么做,因为主线程不能等到“ myThread”通知它。

I have seen a lot of 我看过很多

while(true){
  //wait something from myThread
}

But I can't wait this way! 但是我等不及了!

Any ideas? 有任何想法吗?

Since your main thread is UI, you can send a message to it. 由于您的主线程是UI,因此您可以向其发送消息。

#define WM_USER_EXECUTE_MY_CODE (WM_USER + 1000)

Your UI message loop should process the message: 您的UI消息循环应处理以下消息:

// API code
// LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
// create message map yourself if you're using MFC

if (iMsg == WM_USER_EXECUTE_MY_CODE)
{
    // execute your code must run in main thread
}

And in your worker thread, send UI a message 然后在您的工作线程中,向用户界面发送一条消息

// HWND hwnd = handle to main UI window
// if you need some parameters, send them through WPARAM or LPARAM
SendMessage(hwnd, WM_USER_EXECUTE_MY_CODE, 0, 0);  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM