Thread - How to call a form inside a Thread iTask?

2

In Delphi 10.2, I have a Form A that has a "Task-A" TTask that triggers a StoredProcedure in the Oracle database with Firedac. The StoredProcedure updates a result table that will be used by a form B which has a graph. I would like to call Form B inside a TTask "B-Task", which calls the Forms B with the graph and can return to Form A, while the graph keeps updating in the other forms B! I used the following command to open Form B inside a TTask, BUT FREEZE THE APPLICATION! Thanks for the personal help!

procedure TFormA.SpeedButtonChamaGrafico(Sender: TObject);
var
   Tarefaproc, Tarefagrafico : iTask;
begin

// Chamada da StoredProcedure dentro da TTask ==>  funciona corretamente !!

Tarefaproc := TTask.Create( procedure ()
                            begin
                                 with FDStoredProc1 do
                                 begin
                                      Prepare;
                                      Params[0].Value := StrToInt(EditCenario.Text);
                                      Execproc;
                                  end;
                             end);
          Tarefaproc.Start;


// Logo em seguida, chamada do FormB dentro de outra TTASK ==> DÁ ERRO, congela a aplicação !!

Tarefagrafico := TTask.Create( procedure ()
                               begin
                                   try
                                      Application.CreateForm(TformB,FormB);
                                      FormB.ShowModal;
                                   finally
                                      Freeandnil(formB);
                                   end;
                               end);
Tarefagrafico.Start;
    
asked by anonymous 08.10.2017 / 05:54

1 answer

2

First of all, it is important to point out that everything that is done in the UI of VCL applications happens on the Main Thread, that is, it is no use calling a Form on a thread as this will be processed by the main thread. In these cases it is necessary to use a synchronization method so that only the main thread works at that instant of time, for example:

//considerando que este código está dentro de uma thread
...
TThread.Synchronize(nil, procedure begin
  MeuForm.Show;
end);

That said, you can call your B form outside of a thread and, within it, make queries to the table that "thread A is feeding", no problem.

It is also important to note that database objects (Queries, SPs, etc.) used inside a PRECISAM thread of a connection object of its own, for the exclusive use of that thread. In other words, each thread MUST have its connection to DB.

In order to allow FormA to be accessed while FormB is visible, as already commented the @ junior-moreira, it is only possible to use the Show, without Modal.

Hugs!

    
09.10.2017 / 15:01