要发送消息给线程的最佳途径 [英] Best Way to send message to thread

查看:158
本文介绍了要发送消息给线程的最佳途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是要发送消息给一个线程(不处理),在一段时间(1)循环在C#中运行的最有效和最快的方式/网:

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:


  1. 使用同步队列(如在 阻塞队列和放大器;线程在C#<通讯/ em>的

在运行的消息循环利用系统的WinForms的Application.Run线程上下文和运行application.run订阅的捕捉线程上下文的一封邮件事件发生之前。

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.

使用套接字或命名管道发送线程的消息。

Using socket or named pipe to send the thread a message.

在Linux的我习惯用unix域套要做到这一点,什么是等效的方式做到这一点在Windows?共享内存文件?命名管道?
你觉得呢?

In Linux I am used to do this with unix domain sockets, what is the equivalent way to do it in windows? share memory file? named pipe? What do you think?

推荐答案

我会使用一个生产者/消费者队列,个人。这是有效的WinForms的消息循环是什么,只是在一个Windows窗体特定的方式。

I'd use a producer/consumer queue, personally. That's effectively what the WinForms message loop is, just in a Windows Forms-specific way.

请注意,如果你能够使用.NET 4.0,有<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/system.collections.concurrent%28VS.100%29.aspx>集合的内置的框架,使这很容易。尤其是,使用 BlockingCollection< T> 裹着一个 ConcurrentQueue< ; T> 会做你想要什么

Note that if you're able to use .NET 4.0, there are collections built into the framework which make this very easy. In particular, using a BlockingCollection<T> wrapped round a ConcurrentQueue<T> will do what you want.

我不会亲自使用GeeksCafe码 - 我封装。生产者/消费者自然到自己的类,它的的队列中,而不是治疗的任何的队列中通过扩展方法的方式。特别是,你需要各方正确处理队列中,这意味着它是更好地给它自己的API,在我看来。

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. 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.

这篇关于要发送消息给线程的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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