在使用OmniThread库创建并行任务的程序中,当我尝试访问并行任务中的参数时,参数访问后的代码不会被执行,所以显然任务中止了:
uses
System.SysUtils, System.Classes,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
OtlComm, OtlTask, OtlTaskControl, OtlEventMonitor;
type
TForm1 = class(TForm)
btnStartOTLTask: TButton;
OTLMonitor: TOmniEventMonitor;
procedure btnStartOTLTaskClick(Sender: TObject);
procedure OTLMonitorTaskMessage(const task: IOmniTaskControl; const msg:
TOmniMessage);
private
{ Private-Deklarationen }
FTestTask: IOmniTaskControl;
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ Place a TOmniEventMonitor component on the form,
name it OTLMonitor
and implement the OnTaskMessage event-handler: OTLMonitorTaskMessage }
procedure TestParameters(const ATask: IOmniTask);
var
test: Integer;
begin
ATask.Comm.Send(16); // does execute
test := ATask.Param['From']; // ?? <<<===========================
ATask.Comm.Send(17); // does NOT execute!
end;
procedure TForm1.btnStartOTLTaskClick(Sender: TObject);
begin
if not Assigned(FTestTask) then // prevent multiple tasks
FTestTask := CreateTask(TestParameters, 'TestParameters')
.MonitorWith(OTLMonitor)
.SetParameters(['From', 0, 'To', 99])
.Run
else
MessageDlg('Task is already running!', mtInformation, [mbOK], 0);
end;
procedure TForm1.OTLMonitorTaskMessage(const task: IOmniTaskControl; const msg: TOmniMessage);
begin
Self.Caption := IntToStr(msg.MsgID);
end;
那么访问参数'From'
会出现什么问题?
答案 0 :(得分:2)
我找到了解决方法:
procedure TestParameters(const ATask: IOmniTask);
begin
// this does work:
ATask.Comm.Send(ATask.Param.ByName('From'));
ATask.Comm.Send(ATask.Param.ByName('To'));
// ALSO this does work:
ATask.Comm.Send(ATask.Param['From']);
ATask.Comm.Send(ATask.Param['To']);
end;
procedure TForm1.btnStartOTLTaskClick(Sender: TObject);
begin
if not Assigned(FTestTask) then // prevent multiple tasks
FTestTask := CreateTask(TestParameters, 'TestParameters')
.MonitorWith(OTLMonitor)
// SetParameters does not work:
//.SetParameters(['From', 1, 'To', 99])
// this does work:
.SetParameter('From', 1)
.SetParameter('To', 99)
.Run
else
MessageDlg('Task is already running!', mtInformation, [mbOK], 0);
end;
procedure TForm1.OTLMonitorTaskMessage(const task: IOmniTaskControl; const msg: TOmniMessage);
begin
Memo1.Lines.Add(IntToStr(msg.MsgID));
end;
procedure TForm1.OTLMonitorTaskTerminated(const task: IOmniTaskControl);
begin
FTestTask := nil;
Memo1.Lines.Add('Task terminated');
end;