我已经声明了这些新类型:
type
TRacer = record
name: string;
win, tie, loss, points: integer;
end;
TRacersList = TList<TRacer>;
我在数据模块中有一个如下所示的过程:
procedure DMConnection.getDivision(aList: TRacersList; const game, id: string);
begin
//1) setup the REST params
RESTRequest.Params[0].Value := game;
RESTRequest.Params[1].Value := id;
//2) execute async so UI won't freeze
RESTRequest.ExecuteAsync(procedure
var tmp: TRacer;
ja: TJSONArray;
jv: TJSONValue;
begin
//parse the JSON. The RESTResponse is a TRESTResponse that holds the result of the RESTRequest. I have made a test inside the component (right click -> execute) and it works properly (= I can see the JSON inside the Content property).
ja := TJSONObject.ParseJSONValue(RESTResponse.Content) as TJSONArray;
for jv in ja do begin
tmp.name := jv.GetValue<string>('name');
tmp.win := jv.GetValue<integer>('Wins');
tmp.tie := jv.GetValue<integer>('Ties');
tmp.loss := jv.GetValue<integer>('Loss');
tmp.points := jv.GetValue<integer>('Pts');
aList.Add(tmp);
end;
end);
end;
如果您想知道,这是 JSON 字符串:
[{"name":"payer1","Wins":"1","Ties":"0","Loss":"0","Pts":"3"},{"name":"Velocity","Wins":"0","Ties":"0","Loss":"1","Pts":"0"},{"name":"test2","Wins":"0","Ties":"0","Loss":"0","Pts":"0"}]
在主窗体中,我可以通过这种方式调用该过程:
DMConnection.getDivision(myList, 'mku', 'k2');
我有以下问题。该变量myList: TRacersList
在表单的 OnCreate 和 OnDestroy 事件中创建和释放。如果您尝试运行此代码:
DMConnection.getDivision(myList, 'mku', 'k2');
ShowMessage(myList.Count.toString);
结果为 0。相反,如果我将异步请求放在aList.Add(tmp);
外部(例如,在参数设置之前),则计数为 1。
这意味着当列表在完成处理程序之外时正在填充列表,ExecuteAsync
但当列表在内部时则不会。任何想法?
我已经确认默认情况下同步设置为 True,所以添加
TTHread.Synchronize(nil, procedure
begin
aList.Add(tmp);
end)
将是无用的。我应该怎么办?我想在数据模块中有这个解析/休息的东西,这样我就可以把互联网的东西与我的应用程序实现分开。