gpt4 book ai didi

c++ - XMLHTTPRequest 用于异步轮询 readyState

转载 作者:搜寻专家 更新时间:2023-10-31 01:55:12 24 4
gpt4 key购买 nike

这是我的代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com