This article is written based on Microsoft Windows 7 using
C# and .NET framework 2.0.
Microsoft message queue (MSMQ) is one of the technique with
which you can achieve communication between two application processes running in same
machine, under Windows platform.
To
use MSMQ, you need to add reference System.Messaging explicitly in to your
project and then you can avail its functionalities. Two very basic functions of
MessageQueue class are Send() and Receive().
Send() method sends data to the message queue while
Receive() method reads data from the message queue.
Microsoft
Windows OS have three types of message queuing techniques and those are: -
1. Outgoing queue
2. Private queue
3. System queue
To view a queue, right click on MyCoputer -> Manage,
expand Services and Applications and then expand Message Queuing. All
queue used to enlist here, under the respective category that you have chosen
while creating a message queue.
C# code to send send and receive data:
// Write data:
string
qPath = ".\\Private$\\MyQueue";
MessageQueue
mq;
if
(!MessageQueue.Exists(qPath))
{
mq = MessageQueue.Create(qPath);
}
else
mq = new
MessageQueue(qPath);
Message
msg = new Message();
msg.Label = "TestQueue";
msg.Body = "This
is a test method.";
mq.Send(msg);
// Read data:
try
{
string qPath = ".\\Private$\\MyQueue";
Message msg = new Message();
Message msg = new Message();
MessageQueue msQ = new MessageQueue(qPath);
msg = msQ.Receive();
msg.Formatter = new XmlMessageFormatter(new
Type[] { typeof(string) });
string msgReceived =
msg.Body.ToString();
}
catch
{ }
Possible Errors:
This
is because if you havn’t created any queue or the queue does not exist and you
are trying to use a queue. Conditional check if(!MessageQueue.Exists(qPath)) generally resolve this error.
This is because you have not defined the
respective format of received queue data. Below code can be used to define
formatter.
msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
3. Message Queuing has not been installed on this computer.
This occurs if your system has not installed MSMQ. To install MSMQ in your system, go to Control Panel-> Programs & Features->Turn Windows features on or off -> Microsoft Message Queue (MSMQ) Server -> enable and click OK. If system prompts to restart, please allow it to complete the task.
No comments:
Post a Comment