Delphi 线程等待数据,处理它,然后继续等待 [英] Delphi thread that waits for data, processes it, then resumes waiting

查看:35
本文介绍了Delphi 线程等待数据,处理它,然后继续等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Delphi 中创建一个具有以下特征的线程:

I need to create a thread in Delphi with the following characteristics:

  • 等到主线程将数据添加到共享队列.
  • 处理队列中的所有数据,将结果返回到主线程(对于最后一部分,我将只向主窗口发送消息).处理非常耗时,因此在工作线程处理之前的条目时,可能会将新数据添加到队列中.
  • 继续等待,使用尽可能少的 CPU 周期.

我无法向线程发送消息,因为它没有窗口句柄.

I cannot send messages to the thread, since it does not have a window handle.

我应该使用 WaitForObject 的一些变体吗?如果是这样,那还要等什么呢?如果没有,那我怎样才能让线程等待,然后在新数据进入队列时唤醒它?

Should I be using some variant of WaitForObject? If so, what would the wait be for? If not, then how can I keep the thread waiting, then awake it when new data comes down the queue?

我已阅读 多线程 - Delphi 方式,这似乎没有回答我的问题.也许 OmniThreadLibrary 可以做我需要的;我不知道,因为文档很少.我对线程的了解不够多,无法弄清楚该库是否会在这里提供帮助以及如何使用它(甚至为什么要使用它而不是仅仅使用 TThread 后代).

I've read Multithreading - The Delphi Way, which doesn't seem to answer my question. Perhaps OmniThreadLibrary can do what I need; I can't tell since there's little documentation. I don't know enough about threads in general to figure out if the library will help here and how to use it (or even why to use it instead of just working with TThread descendants).

推荐答案

OmniThreadLibrary 在这里绝对可以帮到你.OTL 发行版中的测试 5 应该可以帮助您入门.

OmniThreadLibrary can definitely help you here. Test 5 from the OTL distribution should help you started.

在此演示中,开始"按钮创建线程并设置一些参数和计时器(如果不需要,您可以在代码中删除它们).更改消息"向线程发送消息,该消息在线程的 OMChangeMes​​sage 方法中处理.线程然后将一些信息发送回客户端(本演示中的 OMSendMessage,但您可以在您将在其中进行工作的同一消息中执行此操作)并且主线程通过 OmniEventMonitor 组件接收此消息.停止"按钮停止工作线程.

In this demo, "Start" button creates the thread and sets some parameters and timer (which you can remove in your code if not needed). "Change message" sends a message to the thread and this message is processed in thread's OMChangeMessage method. Thread then sends some information back to the client (OMSendMessage in this demo, but you can do this in the same message you'll be doing your work in) and main thread receives this message via the OmniEventMonitor component. "Stop" button stops the worker thread.

如果在您的线程忙碌时有更多消息到达,它们将在您的工作方法完成其工作后立即排队和处理.当无事可做时,线程将在进程中使用零 CPU 周期等待下一条消息.

If more messages arrive while your thread is busy, they will be queued and processed as soon as your worker method has completed its work. When there's nothing to do, thread will wait for the next message using zero CPU cycles in the process.

编辑

在 Delphi 2009 及更高版本中,Background Worker 模式提供一个更简单的解决方案.

In Delphi 2009 and above, the Background Worker pattern provides a simpler solution.

这篇关于Delphi 线程等待数据,处理它,然后继续等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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