匿名方法實現多線程同步到主線程執行


高版本DELPHI提供的匿名方法,如果使用的好,可有效地節省代碼。

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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM