Generic Threadsafe Property

那年仲夏 提交于 2019-11-28 07:01:15

Your code is fine and will serialize read/write access to the property. The only comment that I would make is that you do not need to create a separate lock object. You can remove PropLock and lock on Self instead.

I have an almost identical class in my code base. The only differences are:

  1. I use a critical section rather than TMonitor because I still don't trust TMonitor. The early versions had a number of bugs and that dented my confidence. However, I suspect that the TMonitor code is most likely correct by now. So I see no reason for you to change.
  2. I use try/finally with the code that locks and unlocks. This is perhaps a little pessimistic on my part, because it's hard to see how you could usefully recover from exceptions in the getter and setter methods. Force of habit I suppose.

FWIW, my version of your class looks like this:

type
  TThreadsafe<T> = class
  private
    FLock: TCriticalSection;
    FValue: T;
    function GetValue: T;
    procedure SetValue(const NewValue: T);
  public
    constructor Create;
    destructor Destroy; override;
    property Value: T read GetValue write SetValue;
  end;

{ TThreadsafe<T> }

constructor TThreadsafe<T>.Create;
begin
  inherited;
  FLock := TCriticalSection.Create;
end;

destructor TThreadsafe<T>.Destroy;
begin
  FLock.Free;
  inherited;
end;

function TThreadsafe<T>.GetValue: T;
begin
  FLock.Acquire;
  Try
    Result := FValue;
  Finally
    FLock.Release;
  End;
end;

procedure TThreadsafe<T>.SetValue(const NewValue: T);
begin
  FLock.Acquire;
  Try
    FValue := NewValue;
  Finally
    FLock.Release;
  End;
end;

I guess there's really just one way to write this class!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!