views:

362

answers:

2

I'm creating a Windows Service in C#.

What is the best way to listen for messages?? How do I code this properly??

+5  A: 

You don't listen. You configure MSMQ Activation to activate your component when messages arrive. The link has all the details you need, code and configuration.

Remus Rusanu
Yes that was my first choice. Look here for my other question. http://stackoverflow.com/questions/1473179/msmq-not-invoking-com
Jesse Seger
COM activation is the MSMQ 3 model. With MSMQ 4 there is a new activation model, based on Windows Activation Service and WCF.
Remus Rusanu
I will look into Activation Services.
Jesse Seger
+1  A: 

As previously stated, MSMQ Activation is probably the best way, if you can use that. Alternatively, here is code that I've used:

var ts = new TimeSpan(0, 0, 10);
MessageQueue q = GetQueue<T>();
while (true)
{
  try
  {
    Message msg = q.Receive(ts);
    var t = (T)msg.Body;
    HandleMessage(t);
  }
  catch (MessageQueueException e)
  {
    // Test to see if this was just a timeout.
    // If it was, just continue, there were no msgs waiting
    // If it wasn't, something horrible may have happened
  }
}
consultutah
If you use the message enumerator function instead of Receive, you don't have to worry about getting a timeouts when the queue is empty.
Jonathan Allen
Very good consultutah! I have been out for a week and we know what that is like trying to get back into a project, but I will try some things.Grauenwolf, can you please post a short example of Recieve? I've researched this and I'm not completely understanding it. Especially after being on vacation for over a week. Thanks....
Jesse Seger