Delphi异步写入TListBox [英] Delphi asynchronous write to TListBox

查看:176
本文介绍了Delphi异步写入TListBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从多个线程/进程中写入一个名为"listMessages"的TListBox,为了做到这一点,我有两个过程:

I want to write from multiple threads/processes to a TListBox called 'listMessages' and I have this two procedures in order to do this :

1-具有添加对象:

procedure Log(Msg: String; Color: TColor);
begin
  listMessages.Items.AddObject(Msg, Pointer(Color));
  listMessages.ItemIndex := listMessages.Items.Count -1;
end;

2- TIdCriticalSection称为 protectListMessages :

2- With TIdCriticalSection called protectListMessages :

procedure TMainForm.safelyLogMessage(mess : String);
begin
  protectlistMessages.Enter;
  try
    listMessages.Items.Add(mess);
    listMessages.ItemIndex := listMessages.Items.Count -1;
  finally
    protectListMessages.Leave;
  end;
end; 

您能告诉我哪种方法最好(快速+线程安全),或者告诉我第三种方法来从我的线程/进程向TListBox写入消息吗?

Can you tell me which is best(fast + thread safe) or show me a third way to write messages to my TListBox from my threads/processes ?

推荐答案

您的选择都不好.您需要使用选项3!

Neither of your options is any good. You need to use option 3!

重点是,对UI控件的所有访问都必须在主线程上执行.使用TThread.SynchronizeTThread.Queue将UI代码编组到主UI线程上.完成此操作后,该代码将不需要任何进一步的序列化,因为让它在UI线程上运行的真正举动就是对它进行序列化.

The point is that all access to UI controls must execute on the main thread. Use TThread.Synchronize or TThread.Queue to marshal UI code onto the main UI thread. Once you do this, the code will not need any further serialization because the very act of getting it to run on the UI thread serializes it.

代码可能看起来像这样:

The code might look like this:

procedure TMainForm.Log(const Msg: string; const Color: TColor);
var
  Proc: TThreadProcedure;
begin
  Proc :=
    procedure
    begin
      ListBox1.AddItem(Msg, Pointer(Color));
      ListBox1.ItemIndex := ListBox1.Count-1;
    end;

  if GetCurrentThreadId = MainThreadID then
    Proc()
  else
    TThread.Queue(nil, Proc);
end;


在更新中,您指出需要从其他过程写入列表框.使用问题中的任何代码都无法实现这一点.为此,您需要进程间通信(IPC).发送Windows消息是一种合理的方法,但是还有其他IPC选项可用.但是我认为您在使用术语过程时会说错话.我怀疑您的意思不是过程,但是您的意思是我不知道.


In your update you state that you need to write to the list box from a different process. This cannot be achieved with any of the code in the question. You need inter-process communication (IPC) for that. Sending windows messages would be a reasonable approach to take, but there are other IPC options available. But I think that you mis-speak when you use the term process. I suspect that you don't mean process, but what you do mean, I have no idea.

这篇关于Delphi异步写入TListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆