如何用OmniThreadLibrary替换TThread?

时间:2012-10-05 07:43:25

标签: delphi omnithreadlibrary

我习惯于创建TThread后代来进行长时间的数据库操作。我通常的构造看起来像这样:

interface
type
  TMyDBOp = class(TThread)
  private
    FConnection: TADOConnection;
    FCommand1: TADOCommand;
    FCommand2: TADOCommand; // and many more privated objects, vars ...
    procedure InitDB;
    procedure DoneDB;
    procedure DoDBStuff; // and many more procedures and functions to structure the code
  protected
    procedure Execute; override;
  public
    constructor Create; reintroduce;
    property X: T... // and many more properties to set on thread creation
  end;

implementation

constructor TMyDBOp.Create;
begin
  inherited Create(False);
end;

procedure TMyDBOp.InitDB;
begin
  FConnection:= TADOConnection.Create(nil);
  // setup all connection props, setup all other components
end;

procedure TMyDBOp.DoneDb;
begin
  FConnection.Close; // and Free, and Free all other components
end;

procedure TMyDBOp.DoDBStuff;
begin
  // Execute FCommands, do some calculations, call other TMyDBOp methods etc. etc.
end;

procedure TMyDBOp.Execute;
begin
  Try
    Coinitialize;
    InitDB;
    try
      DoDBStuff;
    finally
      DoneDB;
    End;
  Except
    // catch, log, report exceptions ....
  End;
end;

然后我显然使用

这个类
var
  DBOp: TMyDBOp;
begin
  DBOp:= TMyDBOp.Create;
  DBOp.Property1:= xyz; // and set all other props
  DBOp.OnTerminate:= DBOpTerminated; // procedure to catch the thread and read back the results etc. etc.
  DBOp.Resume;
end;

当然我通常将DBOp设置为另一个组件var,以便能够终止,或者等待线程。

现在我想重写这些TThread类并使用OmniThreadLibrary的simillar构造。我该怎么做?我的意思是:用什么基类来定义所有类组件和属性? - 它应该是TOmniWorker的后代吗?那么执行程序在哪里? - 它应该是TObject后代,然后将OTLTaks创建为CreateTask(DBOp.Execute)吗? - 它应该是我作为CreateTask(anonymous method that reads the parameter and calls its Execute)创建的OTLTask的参数传递的TObject吗?

感谢任何提示。

编辑:(基于gabrs对澄清的评论) 我的观点是OTL源中的所有样本/测试只显示一个简单的用法。大多数基本的“单程序”线程。对于我的情况,我需要一个相当复杂的类,子组件和子程序都在一个线程中运行。我正在寻找这样一个阶级的祖先及其设计模式。

0 个答案:

没有答案