最好使用Parallel.BackgroundWorker进行日志记录,使用Parallel.Pipeline进行数据处理。这是一个解决方案的草图(编译,但没有完全实现):
unit PipelineDemo1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
OtlCommon, OtlCollections, OtlParallel;
type
TfrmPipelineDemo = class(TForm)
btnStart: TButton;
btnStop: TButton;
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
private
FLogger : IOmniBackgroundWorker;
FPipeline: IOmniPipeline;
strict protected //asynchronous workers
procedure Asy_LogMessage(const workItem: IOmniWorkItem);
procedure Asy_Monitor(const input, output: IOmniBlockingCollection);
procedure Asy_Parser(const input: TOmniValue; var output: TOmniValue);
procedure Asy_SQL(const input, output: IOmniBlockingCollection);
public
end;
var
frmPipelineDemo: TfrmPipelineDemo;
implementation
uses
OtlTask;
{$R *.dfm}
procedure TfrmPipelineDemo.Asy_LogMessage(const workItem: IOmniWorkItem);
begin
//log workItem.Data
end;
procedure TfrmPipelineDemo.Asy_Monitor(const input, output: IOmniBlockingCollection);
begin
while not input.IsCompleted do begin
if FileExists('0.0') then
output.TryAdd('0.0');
Sleep(1000);
end;
end;
procedure TfrmPipelineDemo.Asy_Parser(const input: TOmniValue; var output: TOmniValue);
begin
// output := ParseFile(input)
FLogger.Schedule(FLogger.CreateWorkItem('File processed: ' + input.AsString));
end;
procedure TfrmPipelineDemo.Asy_SQL(const input, output: IOmniBlockingCollection);
var
value: TOmniValue;
begin
//initialize DB connection
for value in input do begin
//store value into database
end;
//close DB connection
end;
procedure TfrmPipelineDemo.btnStartClick(Sender: TObject);
begin
FLogger := Parallel.BackgroundWorker.NumTasks(1).Execute(Asy_LogMessage);
FPipeline := Parallel.Pipeline
.Stage(Asy_Monitor)
.Stage(Asy_Parser)
.Stage(Asy_SQL)
.Run;
end;
procedure TfrmPipelineDemo.btnStopClick(Sender: TObject);
begin
FPipeline.Input.CompleteAdding;
FPipeline := nil;
FLogger.Terminate(INFINITE);
FLogger := nil;
end;
end.