aurelius objectmanager mulitple task with itask

I'm trying to run some tasks with objectmanager,
ac (TAureliusConnection) connected to firedac and msssql

sometimes i get view_1 is dubplicate, and others just random errors, could send enteties and sql if you like.

procedure TForm1.FormCreate(Sender: TObject);
begin
connection := ac.CreateConnection;
end;

procedure TForm1.asynctest(loops:integer);
var
itasks: TArray;
task:ITask;
todop:TProc;
c:integer;
begin
Randomize;
todop := procedure
var
om:TObjectManager;
r,x:integer;
begin
r := random(10);
x := 0;
om := TObjectManager.Create(connection);
var list_o := OM.Find.list;
try
for var o in list_o do
begin
for var i in o.OrderItemsList do
begin
if i.LineNum = r then
inc(x);
end;
end;
finally
list_o.Free;
end;
om.Free;
TThread.Queue(nil, procedure begin Memo1.Lines.Add(format('Work done, r = %d, x=%d',[r,x])); end)
end;

SetLength(itasks, loops);
for c := 0 to loops-1 do
itasks[c] := TTask.Create(todop);

for task in itasks do
begin
task.Start;
Sleep(100);
end;

try
TTask.WaitForAll(itasks);
except
on e: EAggregateException do Memo1.Lines.Add(e.ToString);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
asynctest(10)
end;

Hi,
I think you need to move

connection := ac.CreateConnection;

from form create event to just above

r := random(10);
x := 0;
connection := ac.CreateConnection;  // move to this line
om := TObjectManager.Create(connection);

Because you are inside a thread context.

1 Like

And each connection must be independent in each thread. You can't use the same connection in two different threads.