Delphi:IdHTTPServer(Indy 10.6)多线程上下文中共享变量的最佳实践

时间:2016-02-10 14:45:22

标签: multithreading delphi indy indy10 idhttp

我有一个TMyIdHTTPServer服务器对象扩展了TIdHTTPServer。我的TMyIdHTTPServer在多线程上下文中共享了一些私有变量(我认为TIdHTTPServer为每个请求创建一个新线程)。

我不是delphi或多线程编程专家,我不确定我的方法是否安全和/或具有良好的性能。

当某些线程读取相同的变量时,会出现性能下降的情况?线程冲突有风险吗?

基本示例:

type
    TMyLogObject = class
       // write string LogMessage in LogFilePath
       procedure WriteLog(const LogMessage, LogFilePath: string);
    end;

    TMyIdHTTPServer = class(TIdHTTPServer)
    private
       FMyLogObject : TMyLogObject;
       FLogPath     : string; 
       procedure  ServerStart;
       procedure  ServerStop;
       procedure  OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
       procedure  OnWorkEnd(ASender: TObject; AWorkMode: TWorkMode);
    public
       constructor Create(const ConfigINI string); reintroduce;
    end;

implementation

   // ConfigINI is a absolute path of server_config.ini
   constructor Create(const ConfigINI string);
   var
     aConfigINI: TIniFile;
   begin
     inherited;

     aConfigINI := TIniFile.Create(ConfigINI);
     try
       // set the path of server log file
       FLogPath := FConfigINI.ReadString('CONFIG', 'LOG_PATH', '');
     finally
       aConfigINI.free;
     end;
   end;

   procedure TMyIdHTTPServer.ServerStart;
   begin
       self.Active  := True;
       FMyLogObject := TMyLogObject.Create;
   end;

   procedure TMyIdHTTPServer.ServerStop;
   begin
       self.Active  := False;
       FMyLogObject.Free;
   end;

   procedure TMyIdHTTPServer.OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
   begin
       AContext.Connection.OnWorkEnd := OnWorkEnd;

       FMyLogObject.WriteLog('StartRequest', FLogPath + 'log.txt');

       AResponseInfo.ContentText := 'Hello!';
   end;

   procedure TMyIdHTTPServer.OnWorkEnd(ASender: TObject; AWorkMode: TWorkMode);
   begin
       FMyLogObject.WriteLog('EndRequest', FLogPath + 'log.txt');
   end;

0 个答案:

没有答案