鉴赏TThreadList 类在LockList和UnlockList 用到TMonitor.Enter(FLock);
TThreadList = class private FList: TList; FLock: TObject; FDuplicates: TDuplicates; public constructor Create; destructor Destroy; override; procedure Add(Item: Pointer); procedure Clear; function LockList: TList; procedure Remove(Item: Pointer); inline; procedure RemoveItem(Item: Pointer; Direction: TList.TDirection); procedure UnlockList; inline; property Duplicates: TDuplicates read FDuplicates write FDuplicates; end; { TThreadList } constructor TThreadList.Create; begin inherited Create; FLock := TObject.Create; FList := TList.Create; FDuplicates := dupIgnore; end; destructor TThreadList.Destroy; begin LockList; // Make sure nobody else is inside the list. try FList.Free; inherited Destroy; finally UnlockList; FLock.Free; end; end; procedure TThreadList.Add(Item: Pointer); begin LockList; try if (Duplicates = dupAccept) or (FList.IndexOf(Item) = -1) then FList.Add(Item) else if Duplicates = dupError then FList.Error(@SDuplicateItem, IntPtr(Item)); finally UnlockList; end; end; procedure TThreadList.Clear; begin LockList; try FList.Clear; finally UnlockList; end; end; function TThreadList.LockList: TList; begin TMonitor.Enter(FLock); Result := FList; end; procedure TThreadList.Remove(Item: Pointer); begin RemoveItem(Item, TList.TDirection.FromBeginning); end; procedure TThreadList.RemoveItem(Item: Pointer; Direction: TList.TDirection); begin LockList; try FList.RemoveItem(Item, Direction); finally UnlockList; end; end; procedure TThreadList.UnlockList; begin TMonitor.Exit(FLock); end;