红鱼儿

使用TkbmMWThreadList实现线程安全列表

早在2008年的2.90.00版本,作者就实现了TkbmMWThreadList,之后在kbmMW 4.40.00版本中,作者使用了Delphi的新特性,实现TkbmMWThreadList的泛型版本,用以实现线程安全的列表。要使用TkbmMWThreadList,首先要引用kbmMWGlobal单元。

然后我们来看看,如何用TkbmMWThreadList实现自己的列表来管理对象。

1.声明列表对象:

FConnectionList:TkbmMWThreadList<TConnectionDataModule>;

上面代码,用FConnectionList来管理TConnectionDataModule对象。

2.建立FConnectionList实例:

FConnectionList := TkbmMWThreadList<TConnectionDataModule>.Create;

3.向对象列表填加被管理的对象:

procedure TMainDatamodule.AddConnection(AConnectionDataModule: TConnectionDataModule);
var
   lst:TList<TConnectionDataModule>;
begin
     lst:=FConnectionList.BeginWrite;
     try
        lst.Add(AConnectionDataModule);
     finally
        FConnectionList.EndWrite;
     end;
end;

调用AddConnection方法,增加一个被管理的对象:

...
AddConnection(cdm);
...

4.清空列表对象:

procedure TMainDatamodule.ClearAllConnection;
var
   i:integer;
   lst:TList<TConnectionDataModule>;
begin
     lst:=FConnectionList.BeginWrite;
     try
        for i:=lst.Count-1 downto 0 do
            lst.Items[i].Free;
        lst.Clear;
     finally
        FConnectionList.EndWrite;
     end;
end;

上面代码,清空列表对象中的所有被管理的对象。

5.读取列表中的被管理的对象:

function TMainDatamodule.GetConnectionPool(AConnectionName: string): TConnectionDataModule;
var
  i: Integer;
  lst:TList<TConnectionDataModule>;
begin
  Result := nil;
  lst:=FConnectionList.BeginRead;
  try
      for i := 0 to lst.Count - 1 do
      begin
        if lst.Items[i].Name = AConnectionName then
        begin
          Result := lst.Items[i];
          Break;
        end;
      end;
  finally
      FConnectionList.EndRead;
  end;
end;

基本实现方法,都写了,可以在线程中安全的使用FConnectionList对象,对TConnectionDataModule进行管理!

 

posted on 2019-04-29 14:56  红鱼儿  阅读(426)  评论(0编辑  收藏  举报