Is this cheating? Exactly which level of hell will I be banished to for spamming these getters/setters in every class I declare?
type
TMyProtectedInt = object
private
FTheInt : integer;
function GetTheInt: integer;
procedure SetTheInt(AValue: integer);
public
property Value : integer read GetTheInt write SetTheInt;
end;
var
AutoLock : TCriticalSection;
implementation
function TMyProtectedInt.GetTheInt: integer;
begin
AutoLock.Acquire;
result := FTheInt;
AutoLock.Release;
end;
procedure TMyProtectedInt.SetTheInt(AValue: integer);
begin
AutoLock.Acquire;
FTheInt := AValue;
AutoLock.Release;
end;
initialization
AutoLock := TCriticalSection.Create;
finalization
AutoLock.Free;
No, its not cheating its a bad way to serialize access to a single resource, mostly because autolock will lock all variables based on TMyProtectedInt not only the one you try to access, but you can easily solve that by moving the autolock variable in the private section of your class (making sure you create and destroy it with your class as well). Then you have the most basic protection scheme there is.