We apologize for the insufficiently clarified previous answer.
You can have infinite amount of queries running through one connection in one thread, but you should not run several queries from several threads through one connection.
Therefore, in the case specified by you, you are right - you should use a separate instance of TMyConnection in each thread. Only, for correct operation, you still have to make a thread-safe access to the TMyStoredProc component on the form, for example, using critical sections. You correctly create a separate instance of TMyConnection in each thread and you can use the code you provided to solve your task by adding a thread-safe access to the TMyStoredProc component on the form. Example:
Code: Select all
var
CriticalSection: TCriticalSection;
...
procedure TForm1.FormCreate(Sender: TObject);
begin
CriticalSection:=TCriticalSection.Create;
end;
procedure TForm1.LoadData;
var
ACloneConnection : TMyConnection;
begin
TThread.CreateAnonymousThread(
procedure
begin
ACloneConnection := TMyConnection.Create(nil);
CriticalSection.Enter;
try
ACloneConnection.LoginPrompt := false;
ACloneConnection.Server := MainConnection.Server;
ACloneConnection.Port := MainConnection.Port;
ACloneConnection.Username := MainConnection.UserName;
ACloneConnection.Password := MainConnection.Password;
ACloneConnection.Database := MainConnection.Database;
ACloneConnection.Open;
MainStoredProc.Close; // This is a TMyStoredProc on my Form.
MainStoredProc.Connection := ACloneConnection;
MainStoredProc.Open;
MainStoredProc.Connection := MainConnection; // This is a TMyConnection on my Form.
finally
if Assigned(ACloneConnection) then
FreeAndNil(ACloneConnection);
CriticalSection.Leave;
end;
end
).Start;
end;
Also, to solve your task, you can use a separate instance of TMyStoredProc in each thread.
Also you can use the TMyConnection.Assign method to set the connection properties. Instead of the lines
Code: Select all
ACloneConnection.Server := MainConnection.Server;
ACloneConnection.Port := MainConnection.Port;
ACloneConnection.Username := MainConnection.UserName;
ACloneConnection.Password := MainConnection.Password;
ACloneConnection.Database := MainConnection.Database;
you can use
Code: Select all
ACloneConnection.Assign(MainConnection);