02 August 2006

Microsoft Message Queue in C#

How to read/write to a Message Queue in c#:

Write:
MessageQueue queue = null;
if (context.Cache["QueueKey"] == null)
{
queue = new MessageQueue(".\private$\queueName", false, true);
context.Cache["QueueKey"] = queue;
}
else
{
queue = (MessageQueue)context.Cache["QueueKey"];
}
queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });
queue.Send(msg);

Read using a windows service:
public partial class QueueService : ServiceBase
{
int _threadCount= 5;
TimeSpan _joinThreadsTimeSpan = TimeSpan.Parse("00:00:02");

Thread[] workerThreads;
QueueReader[] threadHandlers;

public QueueService ()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
arrWorkers = new QueueReader[_threadCount];
threadHandlers = new Thread[_numberOfThreads];

for (int i = 0; i < _threadCount; i++)
{
threadHandlers[i] = new QueueReader();
threadHandlers[i].ServiceStarted = true;

ThreadStart st = new ThreadStart(threadHandlers[i].ExecuteTask);
workerThreads[i] = new Thread(st);
}

for (int i = 0; i < _threadCount; i++)
{
workerThreads[i].Start();
}
}

protected override void OnStop()
{
for (int i = 0; i < _threadCount; i++)
{
threadHandlers[i].ServiceStarted = false;
workerThreads[i].Join(_joinThreadsTimeSpan);
}
}
}

QueueReader Threads
public class QueueReader
{
private MessageQueue _queue = null;
private TimeSpan _timeToWait = TimeSpan.Parse("00:00:05");
private bool _serviceStarted = false;

public QueueReader()
{

_queue = new MessageQueue(".\private$\queueName");
_queue.ReceiveCompleted += new ReceiveCompletedEventHandler(OnReceiveCompleted);
_queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });
_queue.BeginReceive(_timeToWait);
}


public bool ServiceStarted
{
get
{
return _serviceStarted;
}
set
{
_serviceStarted = value;
}
}

public void ExecuteTask()
{
while (_serviceStarted)
{
Thread.Sleep(_timeToWait);
}

Thread.CurrentThread.Abort();
}


private void OnReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
MessageQueue senderQueue = null;

try
{
senderQueue = (MessageQueue)sender;

Message message = senderQueue.EndReceive(e.AsyncResult);


}
catch (MessageQueueException)
{
}
catch (Exception ex)
{
throw(ex);
}
finally
{
_queue.BeginReceive(_timeToWait);
}
}
}

1 comment:

Archimode said...

Gracias por la ayuda me parecio excelente ya que necesito crear un programa que me lea las colas que estan en Private$ e identificar el cambio de estas.

Saludos desde CHILE.

THANK YOU GURU....