如何从主线程完全终止并行任务?
How to completely terminate Parallel task from main thread?
如何从主线程中完全终止这个后台线程,即 OnTerminated
中的代码也不会被执行?
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;
你不能那样做(除了杀死线程,但请不要那样做)。
添加全局标志shouldSkipTerminate
,在创建任务前将其设置为false
,在终止任务前将其设置为true
并检查是否在OnTerminated
.
如何从主线程中完全终止这个后台线程,即 OnTerminated
中的代码也不会被执行?
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;
你不能那样做(除了杀死线程,但请不要那样做)。
添加全局标志shouldSkipTerminate
,在创建任务前将其设置为false
,在终止任务前将其设置为true
并检查是否在OnTerminated
.