简体   繁体   English

向线程发送消息的最佳方式

[英]Best Way to send message to thread

What is the most efficient and fastest way to send message to a thread (not process) that run in while(1) loop in c#/.net: 将消息发送到在c#/。net中while(1)循环中运行的线程(非进程)的最有效和最快速的方法是什么:

  1. Using a synchronized queue (such in Blocking Queues & Thread's Communication in C# ) 使用同步队列(例如在C#阻止队列和线程的通信

  2. Running a message loop Using Application.Run of systems winforms in the thread context and before running the application.run subscribe to an event that capture the messsage in the thread context. 运行消息循环在线程上下文中使用Application.Run系统winforms并在运行application.run之前订阅捕获线程上下文中的消息的事件。

  3. Using socket or named pipe to send the thread a message. 使用套接字或命名管道向线程发送消息。

In Linux I am used to do this with unix domain sockets, what is the equivalent way to do it in windows? 在Linux中,我习惯使用unix域套接字执行此操作,在Windows中执行此操作的方法是什么? share memory file? 分享内存文件? named pipe? 命名管道? What do you think? 你怎么看?

I'd use a producer/consumer queue, personally. 我个人使用生产者/消费者队列。 That's effectively what the WinForms message loop is, just in a Windows Forms-specific way. 这实际上就是WinForms消息循环,只是以Windows窗体特定的方式。

Note that if you're able to use .NET 4.0, there are collections built into the framework which make this very easy. 请注意,如果您能够使用.NET 4.0,那么框架中内置了一些集合 ,这使得这非常容易。 In particular, using a BlockingCollection<T> wrapped round a ConcurrentQueue<T> will do what you want. 特别是,使用包围ConcurrentQueue<T>BlockingCollection<T> ConcurrentQueue<T>将执行您想要的操作。

I wouldn't personally use the GeeksCafe code - I'd encapsulate the producer/consumer nature into its own class which wraps a queue, rather than treating any queue in that way via extension methods. 我个人不会使用GeeksCafe代码 - 我将生产者/消费者性质封装到自己的包装队列的类中,而不是通过扩展方法以这种方式处理任何队列。 In particular, you need all parties to handle the queue correctly, which means it's better to give it its own API in my view. 特别是,您需要所有各方正确处理队列,这意味着最好在我的视图中为其提供自己的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM