1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| procedure TForm1.CallBackgroundTask;
begin
Memo1.Clear;
Label3.Caption := '0';
Label5.Caption := '0';
Label10.Caption := '0';
TTask.Run(procedure
var
I, LCycle, LCpt, LMaxi: Integer;
LAttente: Cardinal;
LSW: TStopWatch;
LNbrTaches: Cardinal;
LListTasks: Array of ITask;
begin
// Désactive le bouton
ChangeButtonState;
// Initialisation des variables
LSW := TStopwatch.StartNew;
LNbrTaches := SpinEdit1.Value;
LAttente := SpinEdit2.Value;
LMaxi := SpinEdit1.MaxValue;
LCycle := 0;
LCpt := 0;
// Défini la taille du spool de tasks
SetLength(LListTasks, LNbrTaches);
// Création du spool de Tasks
for I := 0 to Pred(LNbrTaches) do
begin
LListTasks[I] := TTask.Create(procedure
var
LUtilisation, LIndex: Integer;
begin
LIndex := TInterlocked.Increment(LCpt);
LUtilisation := Random(LMaxi);
Sleep(LUtilisation);
DisplayLog(Format('Tâche %d (%d ms)', [LIndex, LUtilisation]));
end);
end;
// Exécute les Tasks du spool
for I := 0 to Pred(LNbrTaches) do
LListTasks[I].Start;
DisplayLog('Début');
// Boucle d'attente des Tasks qui ne sont pas terminées
while not TTask.WaitForAll(LListTasks, LAttente) do
begin
Inc(LCycle);
Application.MainForm.Update;
end;
DisplayLog('Fin');
LSW.Stop;
// Affiche les stats.
DisplayUsage(LSW.ElapsedMilliseconds, LCycle);
// Ré-active le bouton
ChangeButtonState;
end);
end;
procedure TForm1.DisplayLog(const AMsg: string);
begin
TThread.Synchronize(nil,
procedure
begin
Memo1.Lines.Add(AMsg);
end);
end;
procedure TForm1.ChangeButtonState;
begin
TThread.Synchronize(nil,
procedure
begin
Button1.Enabled := not Button1.Enabled;
end);
end;
procedure TForm1.DisplayUsage(const AValue: Int64; const ACycle: Integer);
begin
TThread.Synchronize(nil,
procedure
begin
Label3.Caption := AValue.ToString;
Label5.Caption := FormatDateTime('nn:ss.zzz', AValue / MSecsPerDay);
Label10.Caption := ACycle.ToString;
end);
end; |
Partager