我正在使用线程,这就是我使用互斥锁来锁定共享资源的原因。锁定的基本用法是将资源放入锁定/解锁块中。
procedure RefreshData;
begin
DataLock;
GetData;
GetSettings;
CheckValues;
...
DataUnlock;
end;
因为总是存在配对的 Lock/Unlock,我开始思考一种简化的锁定/解锁方法,可以在不需要时自动解锁资源。
所以我的想法是引入一个新的过程,该过程将以指向过程的引用作为输入参数。这将使我能够使用匿名方法。
代码可能如下:
type TBaseProc = reference to procedure;
procedure TMyObject.LockMethod(AMeth: TBaseProc);
begin
DataLock;
try
AMeth;
finally
DataUnlock;
end;
end;
procedure TForm1.RefreshData;
begin
MyObject.LockMethod(
procedure
begin
GetData;
GetSettings;
CheckValues;
...
end;
);
end;
这种方式有意义吗?还是有更好甚至更简单的解决方案吗?谢谢和问候。