How to use the MQ?

How to use the MQ?
===================================================================================
Here is an example to use the MQ:

using System;
using System.Messaging;
using System.Drawing;
using System.IO;

namespace ConsoleApplication1
{

---------------------------------------------------
public class Order
{
public int orderId;
public DateTime orderTime;
};

---------------------------------------------------
public class MyNewQueue
{

public static void Main()
{
MyNewQueue myNewQueue = new MyNewQueue();
CreateQueue(".\\myQueue");

myNewQueue.SendMessage();

// Receive a message from a queue.
myNewQueue.ReceiveMessage();

return;
}


public static void CreateQueue(string queuePath)
{
try
{
if(!MessageQueue.Exists(queuePath))
{
MessageQueue.Create(@".\private$\myQueue");
}
else
{
Console.WriteLine(queuePath + " already exists.");
}
}
catch (MessageQueueException e)
{
Console.WriteLine(e.Message);
}
}


public void SendMessage()
{
try
{
Order sentOrder = new Order();
sentOrder.orderId = 3;
sentOrder.orderTime = DateTime.Now;
MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
Message myMessage = new Message(sentOrder);
myQueue.Send(myMessage);
}
catch(ArgumentException e)
{
Console.WriteLine(e.Message);
}

return;
}


public void ReceiveMessage()
{

MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
myQueue.Formatter = new XmlMessageFormatter(new Type[]{typeof(ConsoleApplication1.Order)});
try
{
Message myMessage = myQueue.Receive();
Order myOrder = (Order)myMessage.Body;
Console.WriteLine("Order ID: " +
myOrder.orderId.ToString());
Console.WriteLine("Sent: " +
myOrder.orderTime.ToString());
}
catch (MessageQueueException)
{
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}

return;
}
}
---------------------------------------------------

}

posted @ 2006-10-17 10:32  RobotTech  阅读(253)  评论(0编辑  收藏  举报