[英]Is it correct to use std::async for background tasks inside an internal thread (not from main process's thread)
[英]Change from background thread to main thread
因此,我創建了一個新線程,以便該操作在后台線程上運行:
void ProcessCall(char *szJSON)
{
#ifdef _WIN32
HANDLE hThread = CreateThread(NULL, 0, ProcessOnNewThread, szJSON, 0, NULL);
CloseHandle(hThread);
hThread = NULL;
#endif
}
namespace callEventCallbacks
{
void OnEventDetected(const char *szEvent)
{
// Make sure the callback function is specified
if (callEventInterface.ProcessCallBackJSInterfaceResponse == NULL)
return;
if (!strcmp(szEvent, "EVENT_DETECTED"))
iOLibInterface.ProcessCallBackJSInterfaceResponse (szEventDetectedCallback, NULL, 0);
}
}
namespace
{
DWORD WINAPI ProcessOnNewThread(LPVOID lpvParam)
{
// Obtain the string JSON from the parameter
char *szJSON = (char *)lpvParam;
// Attempt to parse the JSON to rapidjson Document structure - this allocates memory for the json document, the string can be freed after parsing it
Document jsonDocument;
bool validJson = !jsonDocument.Parse<0>(szJSON).HasParseError();
// Obtain the parameters from the JSON based on the operation type
if (!strcmp(szOperation, "RegisterForCardEvent"))
{
if (jsonDocument.HasMember("EventName") && jsonDocument.HasMember("Callback"))
{
// Obtain the event name and callback function name
const char *szEvent = jsonDocument["EventName"].GetString();
const char *szCallback = jsonDocument["Callback"].GetString();
// Store the callback in a required buffer and register the callback for a required card event
if (!strcmp(szEvent, "EVENT_DETECTED"))
{
SPRINTF_S(callEventCallbacks::szEventDetectedCallback, sizeof(callEventCallbacks::szEventDetectedCallback), szCallback);
callEvent.RegisterForCardEvent(callEventCallbacks::OnEventDetected);
}
}
}
}
}
然后,我想將后台線程切換到主線程並繼續操作:(讓switch語句在主線程而不是后台線程上運行)
namespace
{
CJSCallDoc *globalDocument;
void ProcessCallBackJSInterfaceResponse (const char *szCallback, const char **arrayOfParameters, int arraySize)
{
switch (arraySize)
{
case 0:
globalDocument->m_webPage.CallJScript(szCallback);
break;
case 1:
globalDocument->m_webPage.CallJScript(szCallback, arrayOfParameters[0]);
break;
case 2:
globalDocument->m_webPage.CallJScript(szCallback, arrayOfParameters[0], arrayOfParameters[1]);
break;
case 3:
globalDocument->m_webPage.CallJScript(szCallback, arrayOfParameters[0], arrayOfParameters[1], arrayOfParameters[2]);
break;
default:
break;
}
}
}
有誰知道如何做到這一點,並且能夠給我一個想法?
在Windows中,如果希望后台線程在GUI線程上觸發操作,則最常見的事情是將自定義的Windows消息發布或發送到主線程的消息隊列中並對此做出反應。
PostMessage是異步的,因此后台線程將不等待完成,而SendMessage是同步的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.