Einzelnen Beitrag anzeigen

Furtbichler
(Gast)

n/a Beiträge
 
#3

AW: mutiple procedures in threads

  Alt 31. Dez 2013, 13:32
You are free to process all your SaveXXXX() procedures in *one* separate thread. multiple threads is useless as the individual methods have to be processed in order I guess.
I would like to use multi-thread for all the procedures with a status-bar
This is a contradiction: If you want to process all methods simultaneously, there is no need for a status bar.

However, How about this (untested, might be close to Delphi):
Delphi-Quellcode:
Type
TNotifyStringEvent = Procedure (Sender : TObject; msg : string) of Object;
TSaveThread = Class (TThread)
private
  fMsg : String;
  fOnShowStatus : TNotifyStringEvent;
Protected
  Procedure Execute: Override;
public
  Constructor Create; Override;
  OnShowStatus : TNotifyStringEvent Read fOnShowStatus write fOnShowStatus;
End;

Constructor TTSaveThread.Create;
Begin
  Inherited Create(True);
  FreeOnTerminate := true;
End;

Procedure TTsaveThread.ShowStatus (msg : String);
Begin
  fMsg := msg;
  Synchronize(DoShowStatus);
End;

Procedure TSaveThread.DoShowStatus;
Begin
  If Assigned (fOnShowStatus) then fOnShowStatus(Sender, fMsg);
End;

Procedure TTSaveThread.Execute;
Begin
  ShowStatus('Saving Child');
  savechild();
  ShowStatus('Saving Root');
  saveroot();
  ShowStatus('Saving Admin');
  saveToAdmin();
  ShowStatus('Saving To Public');
  saveTopublic();
  ShowStatus('Saving Secret Data');
  saveSecretData();
end;

...
Procedure TMyForm.ButtonClick(Sender : TObject);
Begin
  ProgressBar.Minimum := 1;
  ProgressBar.Maximum := 5;
  ProgressBar.Position := 1;
  myThread := TSaveThread.Create;
  myThread.OnShowStatus := MyShowStatus;
  myThread.OnTerminate := SaveDone;
  myThread.Resume;
End;

Procedure TMyForm.SaveDone (Sender : TObject);
Begin
  Showmessage('Save finished');
End;

Procedure TMyForm.MyShowStatus (Sender : TObject; msg : String);
Begin
  lbProgress.Caption := msg;
  ProgressBar.Step;
End;
This will create a thread which will do the work in the background leaving the form operational. When a step is finished, it calls an event and the subscriber (our form) can update the progress bar and a label.

However, you must include logic to cancel the thread in case your form is closed. Otherwise the event call will access a nonexistent or at least invisible form. Also, you might think that closing the form should be either forbidden, wait for the thread to finish or cancel the thread's execution.

My advice: Study the thread demos thoroughly.

PS: There is a much simpler approach without a thread. just update the progressbar and the label prior to executing each step in the main form. However this puts your form in a blocking state and you have to take care on processing messages in between yourself. I would prefer using a thread and add logic to let the form/thread behave properly on any attempt to close the form.
  Mit Zitat antworten Zitat