在WINDOWS里面使用臨界來保護多線程需要訪問的共享對象,現在,DELPHI有了新的跨平台臨界保護者--System.TMonitor
代碼演示如下:
FConnections := TObjectDictionary<TIdTCPConnection,TDSTCPChannel>.Create;
。。。
procedure TCMServerForm.CMServerTransportDisconnectEvent(Event: TDSTCPDisconnectEventObject);
var
Index: Integer;
begin
if (FConnections = nil) or (Event.Connection = nil) then
Exit;
//進入臨界保護
System.TMonitor.Enter(FConnections);
try
FConnections.Remove(TIdTCPConnection(Event.Connection));
TThread.Synchronize(nil, procedure
begin
//update the connection list box, removing the connection that was just closed
Index := ConnectionsList.Items.IndexOfObject(Event.Connection);
if Index > -1 then
begin
ConnectionsList.Items.Delete(Index);
if ConnectionsList.SelCount = 0 then
SessionIdList.ClearSelection;
end;
end);
finally
// 終止臨界保護
System.TMonitor.Exit(FConnections);
end;
end;