TJson.JsonToObject<T> throws errors in a multi-thread environment

强颜欢笑 提交于 2019-12-13 11:52:46

问题


When using TJson.JsonToObject in a multi-thread environment random access violations occur. I was searching a long time for the problem and I could isolate it with the following code

JSON class

type
   TParameter = class
   public
      FName     : string;
      FDataType : string;
      FValue    : string;
   end;

Testfunction:

procedure Test();
var
   myTasks: array of ITask;
   i : integer;
   max : integer;
begin

  max := 50;
  SetLength(myTasks, max);
  for i := 0 to max  -1  do begin
     myTasks[i] := TTask.Create(procedure ()
       var
          json : string;
          p : TParameter;
       begin
          json := '{"name":"NameOfParam","dataType":"TypeOfParam","value":"ValueOfParam"}';
          p := TJson.JsonToObject<TParameter>(json);
          p.Free;
       end);
     myTasks[i].Start;
  end;

  TTask.WaitForAll(myTasks);
  ShowMessage('all done!');
end;

It's only a code snippet based of a much more complex source. As long I use this code in a single thread everything works without a problem. I'm wondering if there is anything wrong with the code.


回答1:


The method TJSONUnMarshal.ObjectInstance in REST.JsonReflect.pas has a severe bug:

It calls FreeAndNil on a TRttiType instance. This should never be done because all TRtti*** instances are managed by the TRttiContext.

After I removed the FreeAndNil call I could not reproduce the access violation anymore.

Reported as: https://quality.embarcadero.com/browse/RSP-10035

P.S. I also think that https://quality.embarcadero.com/browse/RSP-9815 will affect your code.



来源:https://stackoverflow.com/questions/28341308/tjson-jsontoobjectt-throws-errors-in-a-multi-thread-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!