以前做过的项目中需要对某些变量或设备进行监控,举个例子吧,Unit1中有个全局变量bol,默认为true,现在开个线程监视这个变量,如果变为false则showmessage提示一下,后来功能都实现了,但就是会出现cpu占用率动不动就升到100%的问题,代码如下:
procedure TLook.abc;
begin
  if not Unit1.bol then
  begin
      ShowMessage('False');
      Self.Suspend;
  end; 
end;procedure TLook.Execute;
begin
  while not Self.Terminated do
  begin
      Synchronize(abc);
  end;
end;其它一些项目中有时候也需要用到这种不停监控的功能,我都不敢用线程,只好用个Timer来代替;所以我想请问各位大哥,这种只要程序开着就不停监控的功能正确的方法应该是怎么实现的?
当然,除了在Execute中加sleep外,还有什么方法吗?

解决方案 »

  1.   

    不知道你的线程是否还有其它的功能,但如果只是因为bol值变为false时showmessage。就不用这么麻烦了:
    你这样定义
    procedure setbol(const value:boolean);
    property bol:boolean read fbol write setbol;procedure tform1.setbol(const value:boolean);
    begin
      if fbol=value then 
        exit;
      fbol:=value;
      if not fbol then
         showmessage(......);
    end;在控件里有很多这样的例中
      

  2.   

    全局变量bol在那里更改的就在那里判断一下然后showmessage不行吗?为什么非要用个线程去做???
      

  3.   

    就是这么简单的一个例子,cpu一样跑到100%,不要说更复杂的功能了
      

  4.   

    while not Self.Terminated do
      begin
        if not unit1.bol then
          Synchronize(abc);
        sleep(1);
      end;
      

  5.   

    很感谢各位大哥的帮忙,不过可能大家还没理解我的意思,虽然我写了个例子,但这个例子只是为了让我的意思更清楚一点,我想要知道的是通用的解决方法,请大家不要拘泥于我的例子
    再说白一点吧,怎么样用线程监控而不使cpu上到100%且不用sleep语句