热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

delphiParallel之TTask初试

unitUnit1;interfaceusesWinapi.Windows,Winapi.Messages,System.SysUtils,System.Variants,Syst
unit Unit1;

interface

uses
  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;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  private
    procedure TaskProc(Sender: TObject);
    function FutureEvent(Sender: TObject): string;
  public
    { Public declarations }
  end;


var
  Form1: TForm1;



implementation

{$R *.dfm}

uses
  System.Threading, System.SyncObjs, System.Diagnostics;

procedure TForm1.Button1Click(Sender: TObject);
var
  ATask: ITask;
begin
  ATask := TTask.Run(Self, Form1.TaskProc);
  ATask.Start;
  //阻塞至线程结束
  ATask.Wait;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  ATask: IFuture<string>;
begin
  ATask := TTask.Future<string>(function: string
    begin
      TThread.Sleep(3000);
      Result := DateTimeToStr(Now);
    end);
  //阻塞至线程结束
  Caption := ATask.Value;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  ATask: IFuture<string>;
begin
  ATask := TTask.Future<string>(Self, FutureEvent);
  //阻塞至线程结束
  Caption := ATask.Value;
end;

procedure TForm1.Button4Click(Sender: TObject);
var
  TaskArray: TArray;
  I: Integer;
begin
  SetLength(TaskArray, 5);
  for I := Low(TaskArray) to High(TaskArray) do
    TaskArray[I] := TTask.Run(procedure
      begin
        TThread.Sleep(1000);
      end);
  //阻塞至线程结束
  TTask.WaitForAll(TaskArray);
  ShowMessage('ok');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ReportMemoryLeaksOnShutdown := True;
end;

function TForm1.FutureEvent(Sender: TObject): string;
begin
  Result := DateTimeToStr(Now);
end;

procedure TForm1.TaskProc(Sender: TObject);
var
  I: Integer;
begin
  TThread.Sleep(3000);
  for I := 0 to 10 do
    TThread.Queue(nil, procedure
      begin
        Memo1.Lines.Add(Sender.ClassName);
      end);
end;

end.

 


推荐阅读
author-avatar
as16as1
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有