从其他线程访问VCL

时间:2016-06-27 14:59:06

标签: multithreading delphi thread-safety vcl

我写了一个基于TThread的通信类,它会发送一些数据并收到回复。 我希望方法:

  1. 发送了数据(这是一个非阻塞程序)
  2. 等待回复或超时
  3. 显示在vcl控件中收到的数据
  4. 将控制权交还给来电者
  5. 这是我尝试的方式,

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      for i := 1 to 5 do // send 5 commands
        mycomm.SendCommand();
    end;
    
    procedure TMyComm.ShowData();
    begin
      Form1.Memo1.Lines.Add('Frame received');
    end;
    
    procedure TMyComm.SendCommand();
    begin
        //build frame and put it on interface here
        //...
    
        event.WaitFor(3000);
    
        //show received frame if no timeout in VCL
        //...
    end;
    
    procedure TMyComm.Execute();
    begin
        while not Terminated do
        begin
          if receive() then //blocks until frame is received
          begin
            Synchronize(ShowData); //hangs :-(
            event.SetEvent;
          end;
        end,
    end;
    

    当然这会导致死锁,但是如何实现我的VCL在每个收到的帧后立即更新?

1 个答案:

答案 0 :(得分:0)

您可以使用匿名线程,这只会在线程完成后执行其余代码,将其更改为满足您的需求。 你可以在:

找到AnonThread单位

C:\ Users \ Public \ Documents \ RAD Studio \ 12.0 \ Samples \ Delphi \ RTL \ CrossPlatform Utils

uses
 AnonThread 

var
    GetFrame :TAnonymousThread<Boolean>;

begin
    GetFrame := TAnonymousThread<Boolean>.Create(function : Boolean
    begin
    // Start your execution      
    end,
    procedure (AResult : Boolean)
    begin
    // Wil only execute after the thread has run its course, also safe to do UI updates       
    end,
    procedure (AException : Exception)
    begin
        ShowMessage('Error : ' + AException.Message);
    end);