Indy synchronize ServerTCPExecute

前端 未结 2 1272
心在旅途
心在旅途 2020-12-07 02:36

I\'m using TIDTCPServer component. As I understood event ServerTCPExecute(AContext: TIdContext) is not synchronized. What is the best way of synchronising it?

相关标签:
2条回答
  • 2020-12-07 03:02

    In my application, I'm using this code:

    procedure MainThreadProcedure;
    begin
      ...
    end;
    .
    .
    .
    procedure IdTCPServerExecute(AContext: TIDContext);
    begin
      TIdYarnOfThread(AContext.Yarn).Thread.Synchronize(MainThreadProcedure);
    end;
    

    Be sure to use a critical section or other synchronization object if you need to access main thread variables in ServerTCPExecute

    0 讨论(0)
  • 2020-12-07 03:16

    The correct way is to use Indy's TIdSync class instead of accessing Indy's internal threads directly, eg:

    uses
      ..., IdSync;
    
    type
      TMySync = class(TIdSync)
      protected
        procedure DoSynchronize; override;
      public
        data: string; 
      end;
    
    procedure TMySync.DoSynchronize;
    begin
      // this runs in the main thread
      // use data as needed...
    end;
    
    procedure IdTCPServerExecute(AContext: TIDContext); 
    var
      tmp: string;
      sync: TMySync; 
    begin 
      tmp := ...;
      sync := TMySync.Create;
      try 
        sync.data := tmp; 
        sync.Synchronize;
      finally
        Sync.Free;
      end; 
    end;
    

    Just be careful with any synchronizing you do, whether it be TIdSync or TThread.Synchronize(). If the main thread tries to deactivate the server while the server is trying to sync with the main thread, you will deadlock both the main thread and the server.

    0 讨论(0)
提交回复
热议问题