ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码
当前位置:首页 >> 网络编程 >> Delphi教程 >> delphi Parallel 之 TTask 初试

delphi Parallel 之 TTask 初试(1/2)

来源:网络整理     时间:2017-09-08     关键词:

本篇文章主要介绍了" delphi Parallel 之 TTask 初试",主要涉及到方面的内容,对于Delphi教程感兴趣的同学可以参考一下: unit Unit1;interfaceusesWinapi.Windows, Winapi.Messages, System.SysUtils, System...

unit Unit1;

interfaceuses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
  System.Generics.Collections;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Memo2: TMemo;
    Memo3: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  privatepublic{ Public declarations }end;


var
  Form1: TForm1;



implementation{$R *.dfm}uses
  System.Threading, System.SyncObjs, System.Diagnostics;

procedure TForm1.Button1Click(Sender: TObject);
const
  C = 1000;
var
  TaskArray: arrayof ITask;
  I: Integer;
  ATask: ITask;
begin
  Button1.Enabled := False;

  Memo1.Clear;
  Memo2.Clear;
  Memo3.Clear;

  SetLength(TaskArray, C);

  for I := 0to C - 1dobegin
    TaskArray[I] := TTask.Create(procedurevar
        Id: string;
      begin
        Id := TThread.Current.ThreadID.ToString;
        TThread.Queue(nil, procedurebeginif Memo1.Lines.IndexOf(Id)=-1then
              Memo1.Lines.Add(Id);
            //Memo2.Lines.Add( IntToStr(Memo2.Lines.Count+1) );end);
      end);
    TaskArray[I].Start;
  end;

  TThread.CreateAnonymousThread(procedurevar
      I: Integer;
      Task: ITask;
    J: Integer;
    begin
      I := C;
      while I > 0dobeginfor Task in TaskArray doif Task.Status = TTaskStatus.Completed then
            Dec(I);
      end;

      TThread.Synchronize(nil, procedurebegin
          Memo1.Lines.Add('OK');
          Button1.Enabled := True;
        end);

      //否则有内存泄漏for J := 0to C - 1do
        TaskArray[J] := nil;
     end).Start;

  if TTask.WaitForAll(TaskArray) then
    Memo1.Lines.Add('WaitForAll');
end;
procedure TForm1.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; end; end.

输出结果

1WaitForAll
2712037064470525OK
63272

有时候,输出结果是:

1WaitForAll
270643712043272570526 OK

测试结果:

相关图片

相关文章