【发布时间】:2017-04-26 22:53:22
【问题描述】:
我是 C++ 新手,我正在设计一个需要从 Internet 获取信息的应用程序,我的问题是,如果没有 Internet 连接,或者速度很慢,我的应用程序会冻结几秒钟。我的应用程序也有一个键盘挂钩,所以当我的应用程序冻结时,Windows 也会这样做。
我的应用程序仅适用于 Windows。
这是我的问题的模拟:
std::string instruction;
std::string otherValue;
int timerId;
int main(int argc, char* argv[])
{
StartKeysListener(); //Keyboard Hook
timerId = SetTimer(nullptr, 0, 5000, static_cast<TIMERPROC>(TimerCallback));
MSG msg;
while (GetMessageA(&msg, nullptr, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
VOID CALLBACK TimerCallback(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
{
DownloadInstructions();
}
std::string DownloadInstructions(std::string url)
{
std::string response = HttpRequest(url); //HttpRequest is a function that uses Windows SOCKET to send an http request
if (!response.empty())
{
instruction = response.substr(0, 5);
otherValue = response.substr(6, 15);
}
}
我尝试使用std::async 在新线程上调用“DownloadInstructions”函数,但我不知道如何将服务器响应返回给回调以更新 “指令” 和 “其他值” 变量。
我该如何解决这个问题?我在 Google 上找不到我要查找的内容。
【问题讨论】:
-
将自定义窗口消息发布到 UI 窗口。窗口消息可以只是将数据放入 WPARAM 和 LPARAM 中,也可以将 LPARAM 中的指针传递给包含数据的结构,例如 stackoverflow.com/questions/19144112/…
-
如果你的服务是 RESTful 的,你可以使用 Casablanca。滚动您自己的异步 I/O 将具有挑战性。 casablanca.codeplex.com/wikipage?title=Http%20Client%20Tutorial
标签: c++ multithreading http winapi