我在我的应用程序中使用TThread
,我有很多我想在其中使用的函数。
我使用的函数需要一些时间来完成,因此在线程中使用它们并不理想。这就是为什么我想知道除了复制和放大之外还有其他方法吗?粘贴函数/过程,然后将(可能注入)我的terminated
标志放入函数中。
我不想使用TerminateThread
API!
一个简短的例子:
procedure MyProcedure;
begin
// some work that takes time over a few lines of code
// add/inject terminated flag?!
// try... finally...
end;
procedure TMyThread.Execute;
begin
MyProcedure;
// or copy and paste myprocedure
end;
那么有没有一种有效的方法来编写帮助我terminated
标志的程序/函数?程序/功能也应该是全局的,因此其他功能/程序也可以调用它们。
答案 0 :(得分:10)
一种选择是在过程调用中引入回调方法。 如果回调方法是Assigned(从线程调用时),则进行调用并采取措施。
从其他地方调用MyProcedure
时,将nil传递给过程。
Type
TAbortProc = function : boolean of object;
procedure MyProcedure( AbortProc : TAbortProc);
begin
//...
if (Assigned(AbortProc) and AbortProc) then
Exit;
//...
end;
function MyThread.AbortOperation : Boolean;
begin
Result := Terminated;
end;
我避免传递线程引用而不是回调方法的原因是隐藏了MyProcedure
的线程逻辑(和依赖)。