Bar-
Here's a snippet for code I'm working on that is exactly what
you are trying to do...I think you just need to set it up to be async
using events (This code is from a good Wrox book, Data-Centric .NET
programming with C#). All other code in my service is boilerplate from
VS.NET:
The constructor part:
public QueueService()
{
// This call is required by the Windows.Forms
Component Designer.
InitializeComponent();
MessageQueue mq = new MessageQueue(@".\Private$\MyQueue");
Type[] type = new Type[1];
type[0] = typeof( string );
mq.Formatter = new XmlMessageFormatter( type );
mq.ReceiveCompleted += new
ReceiveCompletedEventHandler(mq_ReceiveCompleted);
mq.BeginReceive();
// TODO: Add any initialization after the
InitComponent call
}
The delegate part:
private void mq_ReceiveCompleted(object sender,
ReceiveCompletedEventArgs e)
{
try
{
MessageQueue queue = (MessageQueue)sender;
Message msg = queue.EndReceive(e.AsyncResult);
StreamWriter s_logFile = new
StreamWriter(@"c:\debuglog.txt");
s_logFile.WriteLine("Recd: {0}", msg.Body.ToString() );
s_logFile.Flush();
s_logFile.Close();
queue.BeginReceive();
}
catch( Exception exc )
{
EventLog eLog = new EventLog();
eLog.WriteEntry(exc.Message, EventLogEntryType.Error);
}
}
-----Original Message-----
From: Moderated discussion of advanced .NET topics.
[mailto:[EMAIL PROTECTED] On Behalf Of Zecharya Bar
Sent: Wednesday, June 04, 2003 9:29 AM
To: [EMAIL PROTECTED]
Subject: [ADVANCED-DOTNET] Message Queue and Windows Service
Hi,
I'm beginning to experiment with Microsoft Message Queues and have run
into a simple problem. I would like a Windows Service I'm creating to
monitor continuously a MSMQ, and upon receiving a message, call another
method. How do I get the service to continually check the queue?
I've tried putting the Receive() function in an infinite loop in the
OnStart method (see code), but of course that keeps the service from
installing!
I'd appreciate any advice!
Bar
*** my code ***
protected override void OnStart(string[] args)
{
string queuePath = @".\private$\myQueue";
MessageQueue myQueue;
if (! MessageQueue.Exists(queuePath))
{
MessageQueue.Create(queuePath);
}
myQueue = new MessageQueue(queuePath);
// ...and now the infinite loop...
while (true)
{
Message myMessage = myQueue.Receive();
ProcessMessage(myMessage.Body.ToString()); // call to another
method
}
}