简体   繁体   English

Delphi 2007 中的 IdThreadComponent (Indy 9) 错误

[英]IdThreadComponent (Indy 9) in Delphi 2007 Error

I'm using IdTCPClient and IdThreadComponent to get some information for a barcode reader.我正在使用 IdTCPClient 和 IdThreadComponent 来获取条形码阅读器的一些信息。 This code, with some changes is working in Delphi 11 and Indy 10 but not in Delphi 2007 and Indy 9:此代码在 Delphi 11 和 Indy 10 中有效,但在 Delphi 2007 和 Indy 9 中无效:

procedure TPkgSendF1.IdThreadComponent1Run(Sender: TIdCustomThreadComponent);
var
  s: String;
begin
  s := IdTCPClient1.ReadLn('&', 20000, 1500);
  TThread.Queue(nil, procedure  // <== Expected @ but received PROCEDURE
                begin
                  ProcessRead(s);
                end);
end;

// [DCC Error] PkgSendF1.pas(239): E2029 Expression expected but 'PROCEDURE' found

procedure TPkgSendF1.ProcessRead(AValue: string);
begin
  Memo1.Text := AValue;
end;

If I don't use the TThread.Queue I miss some readings.如果我不使用 TThread.Queue 我会错过一些读数。 I'll appreciate any help.我会很感激任何帮助。 Francisco Alvarado弗朗西斯科·阿尔瓦拉多

Anonymous methods did not exist yet in Delphi 2007, they were introduced in Delphi 2010. As such, TThread.Queue() in D2007 only had 1 version that accepted a TThreadMethod : Delphi 2007 中尚不存在匿名方法,它们是在 Delphi 2010 中引入的。因此,D2007 中的TThread.Queue()只有一个接受TThreadMethod的版本:

type
  TThreadMethod = procedure of object;

Which means you need to wrap the call to ProcessRead() inside a helper object that has a procedure with no parameters, eg:这意味着您需要将对ProcessRead()的调用包装在一个辅助对象中,该对象具有一个没有参数的procedure ,例如:

type
  TQueueHelper = class
  public
    Caller: TPkgSendF1;
    Value: String;
    procedure DoProcessing;
  end;

procedure TQueueHelper.DoProcessing;
begin
  try
    Caller.ProcessRead(Value);
  finally
    Free;
  end;
end;

procedure TPkgSendF1.IdThreadComponent1Run(Sender: TIdCustomThreadComponent);
var
  s: string;
begin
  s := IdTCPClient1.ReadLn('&', 20000, 1500);
  with TQueueHelper.Create do
  begin
    Caller := Self;
    Value := s;
    TThread.Queue(nil, DoProcessing);
  end;
end;

FYI, Indy (both 9 and 10) has an asynchronous TIdNotify class in the IdSync unit, which you can use instead of using TThread.Queue() directly, eg:仅供参考,Indy(9 和 10)在IdSync单元中有一个异步TIdNotify类,您可以使用它而不是直接使用TThread.Queue() ,例如:

uses
  IdSync;

type
  TMyNotify = class(TIdNotify)
  public
    Caller: TPkgSendF1;
    Value: String;
    procedure DoNotify; override;
  end;

procedure TMyNotify.DoNotify;
begin
  Caller.ProcessRead(Value);
end;

procedure TPkgSendF1.IdThreadComponent1Run(Sender: TIdCustomThreadComponent);
var
  s: string;
begin
  s := IdTCPClient1.ReadLn('&', 20000, 1500);
  with TMyNotify.Create do
  begin
    Caller := Self;
    Value := s;
    Notify;
  end;
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM