Difficulty Creating Threads

Asked

Viewed 213 times

1

I’m trying to create a Thread. But I’m a beginner in the subject. Someone can point out where my code is wrong. It’s not working

Procedure TFormPrincipal.ButtonCompartilharProxClick(Sender: TObject);
begin
  ButtonComp_Voltar.Enabled       := False;
  ButtonComp_SalvArq.Enabled      := False;
  ButtonComp_Agora.Enabled        := False;
  TabControlForm.TabIndex         := 4;
  ProgressBarComp.Min             := 1;
  ProgressBarComp.Max             := ListView_Pessoas_Lista.Items.Count ;
  LabelComp_TituloStatus.Text     := '...Aguarde...';
  LabelComp_StatusProgresso.Text  := '...Iniciando...';
  CDS.Close;
  CDS.CreateDataSet;
  CDS.Open;

  TThread.CreateAnonymousThread(procedure ()
  var
    a :integer;
  begin
    a                               := 0;
    PessoasTable.First;
    while not PessoasTable.Eof do
      begin
      CDS.Insert;
      CDS.FieldByName('Nome').AsString      := PessoasTable.FieldByName('Nome').AsString;
      CDS.FieldByName('Apelido').AsString   := PessoasTable.FieldByName('Apelido').AsString;
      CDS.FieldByName('Endereco').AsString  := PessoasTable.FieldByName('Endereco').AsString;
      CDS.FieldByName('Cidade').AsString    := PessoasTable.FieldByName('Extra1').AsString;
      CDS.FieldByName('Data').AsString      := PessoasTable.FieldByName('Data').AsString;
      CDS.FieldByName('Data_Nascimento').AsString := PessoasTable.FieldByName('Data_Nascimento').AsString;
      CDS.FieldByName('Idade').AsString     := PessoasTable.FieldByName('Idade').AsString;
      CDS.FieldByName('Ocorrencia').AsString:= PessoasTable.FieldByName('Ocorrencia').AsString;
      CDS.FieldByName('Nome_Pai').AsString  := PessoasTable.FieldByName('Filiacao_pai').AsString;
      CDS.FieldByName('Nome_Mae').AsString  := PessoasTable.FieldByName('Filiacao_mae').AsString;
      CDS.FieldByName('Documento').AsString := PessoasTable.FieldByName('Documento').AsString;
        if FileExists(PessoasTable.FieldByName('Foto_Caminho').AsString) then
          begin
          ImagePreviewIncorp.Bitmap.LoadFromFile(PessoasTable.FieldByName('Foto_Caminho').AsString);
          CDS.FieldByName('Foto1').Assign(ImagePreviewIncorp.Bitmap);
          end;
      CDS.Post;
      a     := a+1;
      PessoasTable.next;
 //     Application.ProcessMessages;
      TThread.Synchronize (TThread.CurrentThread,      {Durante o Loop}
        procedure ()
          begin
            LabelComp_StatusProgresso.Text        := 'Incorporando Arquivo: '+PessoasTable.FieldByName('Foto_Caminho').AsString;
            ProgressBarComp.Value:=ListView_Pessoas_Lista.ItemIndex;
          end);
      end;

    TThread.Synchronize (TThread.CurrentThread,
      procedure ()
      begin  {Final}
        if not DirectoryExists('mnt/sdcard/BancodeImagens/Enviar') then
          try
            ForceDirectories('mnt/sdcard/BancodeImagens/Enviar');
          except
          on e: exception do
            ShowMessage('Não foi possível criar o diretório mnt/sdcard/BancodeImagens/Enviar. Erro: '+
                         e.Message);
          end;
      LabelComp_StatusProgresso.Text  := '...Salvando Arquivo...';
      CDS.SaveToFile('mnt/sdcard/BancodeImagens/Enviar/'+GeraNumeroRegistro+'.XML');
      CDS.Close;
      LabelComp_TituloStatus.Text     := 'O Que Deseja Fazer Com O Arquivo?';
      LabelComp_StatusProgresso.Text  := '...Terminado...';
      ProgressBarComp.Value           := ProgressBarComp.Max;
      ButtonComp_Voltar.Enabled       := True;
      ButtonComp_SalvArq.Enabled      := True;
      ButtonComp_Agora.Enabled        := True;
      end);
  end).Start;

end;
  • 1

    "Not working" ? what happens? does not compile? of the execution error?

  • If there is a Datasource attached to your CDS, the operations you perform in the body of thread will trigger on-screen updates that will compromise execution. When on a thread, no operation directly or indirectly affecting the screen may be outside the Synchronize.

  • I was able to solve With the Code below, I don’t know why but I had to transfer the code that would upload an image to a file and write it to a Sqlite table for Synchronize. But another problem has arisen: When I leave my app running in the background to use another app and go back to my app it’s stuck.

1 answer

0

I was able to solve With the Code below, I don’t know why but I had to transfer the code that would upload an image from the file and save it to a Sqlite table for Synchronize.

But another problem came up: When I leave my app running in the background to use another app and go back to my app it’s stuck

var
  a, Qtde:integer;
begin
  with FormPrincipal do
  begin
  ButtonComp_Voltar.Enabled       := False;
  ButtonComp_SalvArq.Enabled      := False;
  ButtonComp_Agora.Enabled        := False;
  TabControlForm.TabIndex         := 4;
  ProgressBarComp.Min             := 0;
  ProgressBarComp.Max             := ListView_Pessoas_Lista.Items.Count ;
  LabelComp_TituloStatus.Text     := '...Aguarde...';
  LabelComp_StatusProgresso.Text  := '...Iniciando...';
  CDS.Close;
  CDS.CreateDataSet;
  CDS.Open;
 // PessoasTable.First;
  TThread.CreateAnonymousThread(procedure ()
  var
    I: Integer;
    Total: Integer;
   begin
    Total := 1;
    while not PessoasTable.Eof do
      begin
        CDS.Insert;
        CDS.FieldByName('Nome').AsString      := PessoasTable.FieldByName('Nome').AsString;
        CDS.FieldByName('Apelido').AsString   := PessoasTable.FieldByName('Apelido').AsString;
        CDS.FieldByName('Endereco').AsString  := PessoasTable.FieldByName('Endereco').AsString;
        CDS.FieldByName('Cidade').AsString    := PessoasTable.FieldByName('Extra1').AsString;
        CDS.FieldByName('Data').AsString      := PessoasTable.FieldByName('Data').AsString;
        CDS.FieldByName('Data_Nascimento').AsString := PessoasTable.FieldByName('Data_Nascimento').AsString;
        CDS.FieldByName('Idade').AsString     := PessoasTable.FieldByName('Idade').AsString;
        CDS.FieldByName('Ocorrencia').AsString:= PessoasTable.FieldByName('Ocorrencia').AsString;
        CDS.FieldByName('Nome_Pai').AsString  := PessoasTable.FieldByName('Filiacao_pai').AsString;
        CDS.FieldByName('Nome_Mae').AsString  := PessoasTable.FieldByName('Filiacao_mae').AsString;
        CDS.FieldByName('Documento').AsString := PessoasTable.FieldByName('Documento').AsString;
        TThread.Synchronize (TThread.CurrentThread,      {Durante o Loop}
          procedure ()
          begin
             LabelComp_StatusProgresso.Text        := 'Total: '+Total.ToString+
                          ', Adicionando Registro: '+PessoasTable.FieldByName('Registro').AsString;
             ProgressBarComp.Value := ListView_Pessoas_Lista.ItemIndex;
             if FileExists(PessoasTable.FieldByName('Foto_Caminho').AsString) then
               CDS.FieldByName('Foto1').Assign(
                CarregaImagemArquivo(PessoasTable.FieldByName('Foto_Caminho').AsString)
                 );
          end);
        CDS.Post;
        Total := Total+1;
        PessoasTable.Next;
      end;

    TThread.Synchronize (TThread.CurrentThread,
      procedure ()
      begin  {Final}
        ProgressBarComp.Max             := ProgressBarComp.Max;
        LabelComp_StatusProgresso.Text  := '...Salvando Arquivo...';
        CDS.SaveToFile('mnt/sdcard/BancodeImagens/Enviar/'+GeraNumeroRegistro+'.XML');
        LabelComp_StatusProgresso.Text  := 'Terminado';
        LabelComp_TituloStatus.Text     := 'O Que Deseja Fazer Com O Arquivo?';
        CDS.Close;
        ButtonComp_Voltar.Enabled       := True;
        ButtonComp_SalvArq.Enabled      := True;
        ButtonComp_Agora.Enabled        := True;
      end);
   end).Start;

    if not DirectoryExists('mnt/sdcard/BancodeImagens/Enviar') then
      try
        ForceDirectories('mnt/sdcard/BancodeImagens/Enviar');
      except
        on e: exception do
          ShowMessage('Não foi possível criar o diretório mnt/sdcard/BancodeImagens/Enviar. Erro: '+
                       e.Message);
      end;
  end;
end;
  • Because the code accesses the visual components that are on mainthread. To access any Visual or non-visual component that was created on Mainthread, you must use Syncronize so that Mainthread stops processing messages thus avoiding a "race condition".

  • Could you show me via code?. I appreciate the help and all clarification.

  • Did you answer your question or create another one? I don’t understand...

  • I answered but created this situation I reported above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.