The Lock keyword

What I miss the most from C# is the lock keyword. Unfortunately Delphi doesn’t (yet) have such a “feature” so we’re stuck making calls to synchronization objects manually. It’s not a big problem actually but can get quite frustrating when you have lots of “protected” code sections.

To overcome this limitation, I came up with a quick and dirty method (thanks to anonymous methods) that would somehow replicate the “lock” behavior:

type
  TLockedCode = reference to procedure;

procedure Lock(const Obj : TObject; const Code : TLockedCode);
var
  CaughtException : Exception;
begin
  CaughtException := nil;

  { Lock the monitor and run the code }
  TMonitor.Enter(Obj);

  try
    Code();
  except
    { Catch the exception and raise it again after the
      unlock code. }
  on Ex : Exception do
    CaughtException := Ex;
  end;

  TMonitor.Exit(Obj);

  { Raise the exception if there was any }
  if CaughtException <> nil then
    raise CaughtException;
end;

Now you can write code like this:

begin
  Lock(SomeObj, procedure begin
    {...}
    { ... Do some "locked" code here! }
    {...}
  end);
end;

Not the prettiest solution (calling anonymous methods is a bit expensive) but it does the trick if you need to write a lot of “locked” code.