等待数据的Delphi线程,对其进行处理,然后恢复等待 [英] Delphi thread that waits for data, processes it, then resumes waiting

查看:289
本文介绍了等待数据的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.

如果在线程繁忙时有更多消息到达,则将在worker方法完成其工作后立即将它们排队并进行处理.当无事可做时,线程将在进程中使用零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天全站免登陆