views:

93

answers:

4

Hi,

I'm a bit new to C# and multithread programming in general but here goes:

I'm working on a system where I would have an class that would be instantiated and then wait for various messages from another running class. How should I go about catching and sending these messages?

Thanks,

PM

+2  A: 

if you are not using .net remoting to send the object between different appdomains.

in simple scenarion :

1- Create a singleton object of your master class.

2- Use Event And Delegate to send the messages between classes.

If you need to send the messages between Appdomains.

1- If the Appdomain does not cross machine boundry than use IPC channel ( .Net 2.0 and later)

2- IF Appdomain crosses machine boundry than , you can use .net remoting.

saurabh
+1  A: 

Use a Producer/Consumer queue. There is a default implementation in .NET 4.0 and there are many sample implementations found on the net. What you want, based on what you describe, is a single-producer / single-consumer queue.

What generally happens is that one thread is deemed a producer and writes messages on to a queue. A separate thread, referred to as the consumer thread, is waiting idle for messages to appear on the queue. Synchronization details as to how these threads cooperate (or not) with each other is implementation-dependent.

James Dunne
A: 

If you're using .Net 3.5, run your sender in a separate thread and pass it a callback method from the listener:

class Program
    {
        static void Main(string[] args)
        {
            Listener listener = new Listener();
            Sender sender = new Sender();
            sender.Send = new TalkDelegate(listener.TalkToMe);
            Thread thread = new Thread(sender.Run);
            thread.IsBackground = true;
            thread.Start();
            listener.Listen();
        }
    }

    delegate bool TalkDelegate(string messageArg);

    class Listener
    {
        bool keepListening = true;

        public bool TalkToMe(string messageArg)
        {
            Console.WriteLine(messageArg);
            return keepListening;
        }

        public void Listen()
        {
            DateTime startTime = DateTime.Now;
            while ((DateTime.Now - startTime) < TimeSpan.FromSeconds(10))
            {
                Thread.Sleep(100);
            }
            keepListening = false;
        }
    }

    class Sender
    {
        public TalkDelegate Send;

        public void Run()
        {
            bool keepTalking = true;
            while (keepTalking)
            {
                keepTalking = Send(DateTime.Now.ToString("HH:mm:ss"));
                Thread.Sleep(1000);
            }
        }
    }
ebpower