c++ - 使用 XMLHTTPRequest 异步轮询 ReadyState

标签 c++ delphi xmlhttprequest

这是我的代码:

var
  xhttp: OleVariant;

xhttp := CreateOleObject('MSXML2.XMLHTTP');
xhttp.Open('GET', URL, True);
xhttp.send();

while xhttp.readyState <> 4 do
begin
  Application.HandleMessage;        
end;

// status property is available only when readyState is complete
if (xhttp.Status = 200) then... 
// do something

在这种情况下,我不想使用事件 onreadystatechange

问题:readyState上轮询值4是否安全,之后我调用Send,或者是否有陷入困境的风险无限循环?


一些事实:

ServerXMLHTTPRequest可以在循环内使用 waitForResponse ,但我想使用 XMLHTTPRequest 组件。 其中指出:

The waitForResponse method is more efficient than polling the readyState property, which is the only way to wait for an asynchronous send using the XMLHTTP component.

最佳答案

如果您担心无限循环,那么只需为循环实现超时即可,例如:

var 
  xhttp: OleVariant; 
  Ticks: DWORD;

  function TimeoutElapsed: Boolean;
  var
    Cur, Elapsed: DWORD;
  begin
    Cur := GetTickCount();
    if Cur >= Ticks then
      Elapsed := Cur - Ticks
    else
      Elapsed := (MAXDWORD - Ticks) + Cur;
    Result := (Elapsed >= 15000);
  end;

begin
  xhttp := CreateOleObject('MSXML2.XMLHTTP'); 
  xhttp.Open('GET', URL, True); 
  xhttp.send(); 

  Ticks := GetTickCount();
  while (xhttp.readyState <> 4) and (not TimeoutElapsed()) do
  begin
    if MsgWaitForMultipleObjects(0, nil, False, 1000, QS_ALLINPUT) = WAIT_OBJECT_0 then
      Application.ProcessMessages();         
    Ticks := GetTickCount();
  end; 

  // status property is available only when readyState is complete 
  if xhttp.readyState = 4 then
  begin
    if (xhttp.Status = 200) then...  
  end;
end;

关于c++ - 使用 XMLHTTPRequest 异步轮询 ReadyState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8655687/

相关文章:

javascript - 415(不支持的媒体类型)错误

javascript - Adobe AIR 和多个 XMLHttpRequest ……很奇怪

delphi - 如何在嵌入到我的应用程序中的 DLL 中制作表单?

delphi - Delphi XE2 中的类助手和类拦截器

c++ - 使用流的线程安全日志记录

c++ - 将 uintptr_t 转换为 bool 会多次减慢 SSO 基准测试

delphi - 是否有与 TIniFiles 相同的函数或单元不会保存到文件?

javascript - 我可以向另一个域发出 XMLHttpRequest 吗?

c++ - 如何检查我的代码是否在 GCC 中重新编译?

c++ - 是否有某种包含 Linux 或 gcc 的特殊(内存)地址的列表?