views:

1589

answers:

1

Hi ,

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) Using a synchronized queue (such in http://www.geekscafe.net/post/Blocking-Queues-Threade28099s-Communication-in-C.aspx)

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.

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? share memory file? named pipe? What do you think?

Thanks, Eyal

+4  A: 

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

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.

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.

Jon Skeet
producer/consumer queue class as in http://www.albahari.com/threading/part2.aspx?
Eyalk
Thanks Jon, will the producer/consumer queue will be faster than named pipe to transfer the message?
Eyalk
@Eyalk: I suspect so - but benchmark it if you're particularly concerned. It has the advantage of allowing object references to be transferred directly, rather than a named pipe which would basically force you to serialize/deserialize.
Jon Skeet