16

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 Blocking Queues & Thread’s Communication in 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.

  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?

svick
  • 236,525
  • 50
  • 385
  • 514
Eyalk
  • 465
  • 1
  • 5
  • 15

1 Answers1

15

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • producer/consumer queue class as in http://www.albahari.com/threading/part2.aspx? – Eyalk Dec 20 '09 at 13:08
  • Thanks Jon, will the producer/consumer queue will be faster than named pipe to transfer the message? – Eyalk Dec 20 '09 at 13:09
  • @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 Dec 20 '09 at 13:38
  • Is that always an advantage though? I think there's a certain safety inherent in being forced not to do that. – Tom May 27 '11 at 04:24
  • @Ton: It depends on what you're doing. If you've already got an immutable message format, then it's clearly more efficient to just pass a reference around than serialize and deserialize. It also lets you use data structures which *can't* be easily serialized. But yes, it also reduces isolation. – Jon Skeet May 27 '11 at 05:23
  • @Eyalk: Page 119 of the [Albahari PDF](http://www.albahari.info/threading/threading.pdf) – DefenestrationDay Apr 09 '12 at 14:23