Benny Benny - 4 years ago 148
C# Question

How to implement a message pump in Non-UI thread in .NET?

I am reading this blog: Use Threads Correctly, and I am wondering:

How to implement a message (Note: I don't mean Windows Message here) pump in a non-UI thread?

What I want is that the message can be an object or a command, say an

Action<T>
/
Func<T>
, etc.
Do I have to use separate queue for different type of message? Say one queue for object, one queue for
Action<T>
/
Func<T>
?

Given that the type of messages vary, how to implement it?

EDIT:

What I want to complete is a producer/consumer model, producer/consumer share queue for communication, the queue can not only contain object for the consumer to consume, but also some 'command' can be passed to the consumer for execution.

Answer Source

Made this a seperate answer for code formatting

Ok so after reading your update I think you want what I describe in the "second case" you simply want

Broadcast<T>("Foo") 

where T is a delegate.

Then your consumer will do

Subscribe<T>("Foo",HandlerMethod)

So a producer consumer scenario would look like this

internal static class MessagePump
    {

        public static void Subscribe<T>(String foo, Action<String> handlerMethod)
        {
            throw new NotImplementedException();
        }

        public static void BroadcastMessage<T>(String foo, Action<String> someAction)
        {
            throw new NotImplementedException();
        }
    }

    public class Producer
    {
        void SendMessage()
        {
            MessagePump.BroadcastMessage<Action<String>>("Foo", SomeAction);
        }

        void SomeAction(String param)
        {
            //Do Something
        }
    }


    public class Consumer
    {

        public Consumer()
        {
            MessagePump.Subscribe<Action<String>>("Foo", HandlerMethod);
        }

        void HandlerMethod(String param)
        {
            // Do Something
        }

    }

This is just something off the top of my head and is a contrived example so take it with a grain of salt. This is nearly exactly what I am doing in the courier framework I posted earlier. You may want to dive into that code to get a more concrete implementation example.

You need to think about how you will manage consumers, how you validate Broadcast and subscriptions and for your specific case how are you going to ensure the delegate you are passing around is invoked correctly? Or do you care?

Does this help?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download