How to completely terminate Parallel task from main thread?

665 views Asked by At

How can I completely terminate this background thread from the main thread, i.e. that not even the code in OnTerminated will be executed?

uses
  CodeSiteLogging,
  OtlParallel, OtlTaskControl, OtlTask;

procedure TForm2.btnParallelAsyncClick(Sender: TObject);
begin
  CodeSite.Send('btnParallelAsyncClick 1');

  Parallel.Async(
    procedure(const task: IOmniTask)
    var
      a: Integer;
    begin
      // executed in background thread:
      a := 1 + 1;
      Sleep(2000);
      CodeSite.Send('Executed in Async Thread', a);

      task.Invoke( // used to execute code in main thread
        procedure
        begin
          CodeSite.Send('task.Invoke executed in main thread', a);
        end);

      Sleep(2000);
      CodeSite.Send('Again executed in Async Thread', a);
    end,
    Parallel.TaskConfig.OnTerminated(
    procedure(const task: IOmniTaskControl)
    begin
      // executed in main thread:
      CodeSite.Send('After background thread termination: Executed in Main Thread');
    end
    )
    );

  CodeSite.Send('btnParallelAsyncClick 2');
end;
1

There are 1 answers

6
gabr On BEST ANSWER

You can't do that (apart from killing the thread, but please don't do that).

Add a global flag shouldSkipTerminate, set it to false before creating the task, set it to true before you terminate the task and check if this flag is set in OnTerminated.