1) Create a console application in C#
2) Declare class level variable
static bool StopThread = false;
2) Write function to get message queue instance
private static MessageQueue GetStringMessageQueue()
{
MessageQueue msgQueue = null;
string queueName = @".\private$\MyStringQueue";
if (!MessageQueue.Exists(queueName))
{
msgQueue = MessageQueue.Create(queueName);
}
else
{
msgQueue = new MessageQueue(queueName);
}
return msgQueue;
}
{
MessageQueue msgQueue = null;
string queueName = @".\private$\MyStringQueue";
if (!MessageQueue.Exists(queueName))
{
msgQueue = MessageQueue.Create(queueName);
}
else
{
msgQueue = new MessageQueue(queueName);
}
return msgQueue;
}
3) Create function to send message to queue
private static void SendStringMessageToQueue()
{
while (StopThread == false)
{
string msg = Console.ReadLine();
if (msg == "x")
{
Console.WriteLine("Stopping write thread...");
StopThread = true;
break;
}
else
{
MessageQueue msgQueue = GetStringMessageQueue();
msgQueue.Send("New Message send to message queue at " + DateTime.Now.ToString() + "- " + msg);
}
}
}
4) Create function to read message
private static void ReadStringMessageFromQueue()
{
MessageQueue msgQueue = GetStringMessageQueue();
msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
Message msg;
while (StopThread == false)
{
if (StopThread == true)
{
Console.WriteLine("Stopping read thread...");
break;
}
try
{
msg = msgQueue.Receive(new TimeSpan(0, 0, 2));
Console.WriteLine(msg.Body.ToString());
}
catch (Exception ex)
{
}
}
}
5) Now create threads within static main method
static void Main(string[] args)
{
Console.WriteLine("Press x to stop thread");
Thread sendMsgThread = new Thread(new ThreadStart(SendStringMessageToQueue));
Thread readMsgThread = new Thread(new ThreadStart(ReadStringMessageFromQueue));
sendMsgThread.Start();
readMsgThread.Start();
}
No comments:
Post a Comment