简体   繁体   English

OnDataChange内部的代码多次执行

[英]Code inside OnDataChange executed multiple time

I have a TDatasource linked to a TTable and I have some code executed inside Datasource.OnDataChange. 我有一个链接到TTable的TDatasource,并且在Datasource.OnDataChange内部执行了一些代码。

My problem is, when I execute a TTable.First or TTable.Last, the code inside OnDataChange is executed for each record until the cursor reaches the first or last position (I suppose is the same with TTable1.MoveBy). 我的问题是,当我执行TTable.First或TTable.Last时,将对每个记录执行OnDataChange内部的代码,直到光标到达第一个或最后一个位置为止(我想与TTable1.MoveBy相同)。

How can I make sure my code inside OnDataChange is executed only once, at the end of the process ? 在流程结束时,如何确保OnDataChange中的代码仅执行一次?

I've had to deal with a similar situation recently. 我最近不得不处理类似的情况。 In my case, as an example, my code in the OnDataChange event was intended to adjust the column widths of an associated TDBGrid according to the latest data in the associated Dataset . 以我为例,我的OnDataChange事件中的代码旨在根据关联的Dataset的最新数据来调整关联的TDBGrid的列宽。 I needed this adjustment to occur only when the data changed, but OnDataChange appeared to execute multiple times in succession. 我只需要在数据更改时进行此调整,但是OnDataChange似乎要连续执行多次。

So, how to make it execute the code only once? 那么,如何使它仅执行一次代码?

I chose to use a Boolean flag to limit the execution of the code in the OnDataChange event to only when that flag is set to True. 我选择使用Boolean标志将OnDataChange事件中代码的执行限制为仅当该标志设置为True时。 Something like this... (basic example code) 像这样...(基本示例代码)

var
  bLoading: Boolean;

procedure TfrmMain.btnExecuteSQLClick(Sender: TObject);
begin
  qry.SQL := memo.Lines;
  bLoading := True; // set flag to true so code in OnDataChange will execute
  qry.Open;
end;    

procedure TfrmMain.DataSource1OnDataChange(Sender: TObject; Field: TField);
begin
  if bLoading then // checks if your flag is set to true
  begin
    // insert the code you want to run only once here
    ...
    bLoading := False; // then set flag to false to prevent repetitive execution
  end;
end;

I'm not sure if this helps you, and I know it doesn't answer the second part of your question "at the end of the process", but maybe just the idea of using Boolean flags will give you some inspiration to progress with your problem. 我不确定这是否对您有帮助,而且我知道它不能“在流程结束时”回答您问题的第二部分,但也许只是使用布尔标志的想法会给您一些启发你的问题。 It's a useful technique, and in the world of multithreaded programming they've even given it a special name. 这是一种有用的技术,在多线程编程领域,他们甚至给它起了一个特殊的名字。 They call it a mutex !!! 他们称它为mutex It's just a Boolean flag. 它只是一个布尔标志。 Either the door is open, or it's closed. 门是开着的还是关着的。 Once it's opened, make sure you shut the door behind you to prevent uninvited guests from crashing the party! 打开门后,请确保您关闭了身后的门,以防止不请自来的客人摔倒派对!

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

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