繁体   English   中英

delphi xe2正确处理从线程创建的指针,该指针正在发送到主线程

[英]delphi xe2 proper disposal of a pointer created from a thread which pointer is being sent to main thread

我想问几个问题,让我先向您解释一下事情,您可以在本文下方看到问题。 我创建了一个多线程应用程序,该程序可以从数据库读取和更新数据。 线程使用sendmessage与主线程通信。 我将指针TRecord传递给sendmessage并将指针放置在主线程中。 以下是显示流程结构的代码段:

const WM_MY_MESSAGE = WM_USER + 0;

PTestPointerRecord : ^TTestPointerRecord;
TTestPointerRecord = record
  i : integer;
end;

这是扩展的TThread类的execute事件。 除非线程被暂停或终止,否则它将连续运行。

procedure TSampleThreadClass.Execute;
var
  TestPointerRecord : PTestPointerRecord;
  FConnection : TConnectionObject;
  FQuery : TQueryObject;
begin
  while not Terminated do
  begin
    New(PTestPointerRecord);
    FConnection := TConnectionObject.Create(nil);
    FQuery := TQueryObject.Create(nil);
    try
      FConnection.connectionstring := 'path';
      FConnection.loginPrompt := False;
      FConnection.open;

      FQuery.connection := FConnection;
      FQuery.close;
      FQuery.sql.clear;
      FQuery.sql.add('select column1, column2 from table');
      FQuery.open;

      PTestPointerRecord.i := 0;
      SendMessage(frmMain.handle, WM_MY_MESSAGE, 0, integer(PTestPointerRecord));
    finally
      FQuery.close;
      FConnection.disconnect;

      FreeAndNil(FQuery);
      FreeAndNil(FConnection);

      sleep(250);
    end;
  end;  
end;

这是从线程接收消息的事件。

procedure TfrmMain.message(msg : TMessage);
var
  TestPointerRecord : PTestPointerRecord;
begin
  TestPointerRecord := PTestPointerRecord(msg.lParam);
  try
    edit1.Text := inttostr(TestPointerRecord.i);  
  finally
    Dispose(TestPointerRecord);
  end;
end;

该应用程序将用作服务类型的应用程序,该应用程序将一直持续运行。

问题:
1.我是否正确放置了指针?
2.当我在应用程序运行时检查任务管理器时,发现在“进程”选项卡下,我注意到Memory(私有工作集)不断增加。 这样好吗

关于所有

我尝试过建议David Heffernan使用单独的句柄而不是使用主窗体的句柄。 这个建议并没有真正解决问题,但多亏了David,他值得一用,因为他对使用主窗体的句柄接收消息并且重新绘制或重新创建窗口时可能出现的问题做了重点说明。

通过更深入地探索我的代码,进行调试,反复试验。 我发现在创建连接并查询数据库时问题再次发生。 注意,我正在使用ZeosLib连接到数据库,似乎每次线程循环执行数据库操作时,工作的专用内存都在不断增加,这是我不确定Zeoslib是否完全线程安全的。 所以我改用ADO,一切顺利。 工作专用内存保持稳定。

感谢您的所有帮助。

暂无
暂无

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

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