从另一个线程c ++ Windows窗体应用程序更新UI

时间:2017-05-27 15:54:38

标签: c++ multithreading user-interface windows-forms-designer

我想从我用这个函数创建的线程更新ui线程:

CreateThread

这是我的代码

[STAThread]
void Main(array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);

gRecvSockThread = CreateThread(NULL, 0, recvSocket, NULL, 0, NULL);

MyApp::MyForm form;
Application::Run(%form);
}

DWORD WINAPI recvSocket(void *arg) {

char recvbuf[8];
RtlZeroMemory(recvbuf, 8);
while (gSocket->getStateSocket() != -1) {
    int iResult = recv(gSocket->getSocketFD(), recvbuf, 8, MSG_WAITALL);
    if (iResult > 0) {
        if (strcmp("accepted", recvbuf) == 0) {
            //updateUIValidated(); //here I would like to access a label and make it visible for example..
        }
        else {
            //updateUIRejected();
        }
    }

}
return 0;
}

1 个答案:

答案 0 :(得分:0)

使用System::Threading;代替CreateThread解决并创建委托属性。 使用将更新UI的方法绑定此属性:

delegateUpdateUI = gcnew UpdateUI(this, &MyForm::UpdateUIMethod);

然后在我的主题上我打电话:

Invoke(delegateAcceptedUI);

结束:)