在 C# 中的线程之间发送消息 [英] Sending messages between threads in C#
问题描述
如何在线程之间发送和接收消息?
How can I send and receive messages between threads?
推荐答案
一个解决方案是共享一个并发队列,例如(尽管它的名字)ConcurrentQueue.这将允许您将一个对象从一个线程入队,并使另一个线程(或其他线程)从队列中出队.由于它是通用解决方案,您可以传递强类型项,从 string
到 Action
的任何内容都可以,当然也可以传递您自己的自定义消息类.
One solution would be share a concurrent queue, for example (albeit its name) ConcurrentQueue. This will allow you to enqueue an object from one thread and have the other thread (or others threads) dequeue from the queue. As it is a generic solution, you may pass strongly typed items, anything from string
to Action
will do, or your own custom message class of course.
这种方法只有一个限制,ConcurrentQueue
类仅从 .NET 4.0 开始可用.如果您需要在以前版本的 .NET 中使用它,您需要寻找第三方库.例如,您可以采用 来自单声道的 ConcurrentQueue 来源.
Threre is just one limitation with this approach, the class ConcurrentQueue
is only available from .NET 4.0 onwards. If you need this for a previous version of .NET you need to look for a third party libary. For example you can take the source for ConcurrentQueue from mono.
这些队列工作的一般方法是使用链表,并且它们使用自旋进行同步来为乐观并发控制提供资源.据我所知,这是可变大小并发队列的最新技术.现在,如果您事先知道消息负载,您可以尝试固定大小的方法或有利于入队和出队而不是增长的解决方案(这将是基于数组的队列).
The general approach over which those queues work is by having a linked list and they resource to optimistic concurrency control using spinning for synchronization. As far as I know, this is the state of art for concurrent queues of variable size. Now, if you know the message load beforehand you can try a fixed size approach or a solution that favors enqueue and dequeue over growing (that would be an array based queue).
完整披露(根据 faq):我是其中一个第三方库的作者...Theraot.Collections.ThreadSafe.SafeQueue
下找到底层结构,它是一个数组的链表(保存在一个对象池中),通过这种方式,我们不需要复制数组以增长(因为我们只是在列表中添加另一个节点),并且我们不需要经常依赖同步机制(因为添加或删除项目不会经常修改列表).
Full disclouser (according to faq): I'm the author of one of those third party libraries... my libraries (nuget available), it includes a backport ConcurrentQueue
for old versions of .NET, based on a custom implementation. You can find the underlaying structure under Theraot.Collections.ThreadSafe.SafeQueue
, it is a linked list of arrays (which are kept in an object pool), by doing it this way, we do not need to copy the arrays to grow (because we just add another node to the list), and we do not need to rely on synchronization mechanisms as often (because adding or removing an item does not modify the list often).
注意:这个问题曾经链接到托管在另一个存储库上的 HashBucket,并且是我对该问题的旧解决方案.该项目已停产,请使用我上面提到的版本.
Note: this question used to link to HashBucket, which is hosted on another repository, and was my old solution for the problem. That project is discontinued, please use the version I mention above.
这篇关于在 C# 中的线程之间发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!