unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Refresh: TButton;
    Memo1: TMemo;
    Log: TMemo;
    procedure RefreshClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    procedure CancelParallelResolveHostnames;
    procedure StartParallelResolveHostnames;
    { Private declarations }
  private
    FAddressToProcess: TStrings;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  OtlCommon,
  OtlSync,
  OtlTaskControl,
  OtlParallel;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FAddressToProcess := Memo1.Lines;
end;

var
  FParallelResolveHostnames: IOmniParallelSimpleLoop;
  FParallelResolveHostnamesCancelToken: IOmniCancellationToken;

procedure TForm1.StartParallelResolveHostnames;
var
  TaskConfig: IOmniTaskConfig;
begin
  Log.Lines.Add(Format('StartParallelResolveHostnames.Begin', []));
  FParallelResolveHostnamesCancelToken := CreateOmniCancellationToken;
  TaskConfig := Parallel.TaskConfig;
  TaskConfig.SetPriority(TOTLThreadPriority.tpLowest);

  FParallelResolveHostnames := Parallel               //
    .For(0, FAddressToProcess.Count - 1)              //
    .TaskConfig(TaskConfig)                           //
    .CancelWith(FParallelResolveHostnamesCancelToken) //
    .NoWait                                           //
    .OnStop(
    procedure
    begin
      Log.Lines.Add(Format('FParallelResolveHostnames.Stop', []));
    end); //
  FParallelResolveHostnames.NoWait.Execute(
    procedure(i: Integer)
    begin
      Log.Lines.Add(Format('Resolving.Begin %d', [i]));
      Sleep(1000);
      Log.Lines.Add(Format('Resolving.End %d', [i]));
    end);
  Log.Lines.Add(Format('StartParallelResolveHostnames.End', []));
end;

procedure TForm1.CancelParallelResolveHostnames;
begin
  Log.Lines.Add(Format('CancelParallelResolveHostnames.Begin', []));
  if Assigned(FParallelResolveHostnamesCancelToken) then
  begin
    Log.Lines.Add(Format('FParallelResolveHostnamesCancelToken.Signal', []));
    FParallelResolveHostnamesCancelToken.Signal;
  end;
  if Assigned(FParallelResolveHostnames) then
  begin
    Log.Lines.Add(Format('FParallelResolveHostnames set to nil', []));
    FParallelResolveHostnames := nil;
    FParallelResolveHostnamesCancelToken := nil;
  end;
  Log.Lines.Add(Format('CancelParallelResolveHostnames.End', []));
end;

procedure TForm1.RefreshClick(Sender: TObject);
begin
  CancelParallelResolveHostnames;
  StartParallelResolveHostnames
end;

end.
