私はC++を初めてお使いで、インターネットから情報を取得する必要があるアプリケーションを設計しています。インターネットに接続できない場合や、アプリケーションは数秒間フリーズします。私のアプリケーションにはキーボードへのフックも付いているので、アプリケーションがフリーズするとWindowsも動きます。新しいスレッドでhttpリクエストを送信するC++
私のアプリケーションは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」関数を呼び出す試してみましたが、私は更新するコールバックにサーバの応答を返す方法がわかりません"命令"および"otherValue"変数。
どうすればこの問題を解決できますか? Googleで探しているものが見つかりませんでした。
UIウィンドウにカスタムウィンドウメッセージを投稿します。ウィンドウメッセージはWPARAMとLPARAMにデータを置くことも、LPARAMのポインタを渡すこともできます。データが入っている構造体に渡します。たとえばhttp://stackoverflow.com/questions/19144112/how-can-worker-threads-communicate -with-main-ui-thread –
あなたのサービスがRESTfulなら、Casablancaを使うことができます。独自の非同期I/Oをローリングすることは難しいでしょう。 https://casablanca.codeplex.com/wikipage?タイトル=のHttp%20Client%20Tutorial –