这是我的代码:
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/