📄 program.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Messaging;
using System.Threading;
namespace MSMQ.Async
{
class Program
{
static ManualResetEvent signal = new ManualResetEvent(false);
static void Main(string[] args)
{
//CreateQueue();
SendMessage();
AsyncReceiveMessage();
}
/// <summary>
/// 通过Create方法创建使用指定路径的新消息队列
/// </summary>
/// <param name="queuePath"></param>
private static void CreateQueue()
{
try
{
if (!MessageQueue.Exists(".\\myAsyncQueue"))
{
MessageQueue.Create(@".\private$\myAsyncQueue", true);
}
}
catch (MessageQueueException e)
{
Console.WriteLine("创建队列出错,原因:" + e.Message);
}
}
/// <summary>
/// 发送消息到队列
/// </summary>
private static void SendMessage()
{
MessageQueue myQueue = new MessageQueue(".\\private$\\myAsyncQueue");
if (myQueue.Transactional)
{
Book book = new Book();
book.BookId = 1001;
book.BookName = "ASP.NET";
book.BookAuthor = "ZhangSan";
book.BookPrice = 88.88;
Message message = new Message(book);
message.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.Async.Book) });
MessageQueueTransaction myTransaction = new MessageQueueTransaction();
myTransaction.Begin();
myQueue.Send(message, myTransaction);
myTransaction.Commit();
Console.WriteLine("消息成功发送到队列!");
}
}
/// <summary>
/// 异步接收消息
/// </summary>
private static void AsyncReceiveMessage()
{
MessageQueue myQueue = new MessageQueue(".\\private$\\myAsyncQueue");
if (myQueue.Transactional)
{
MessageQueueTransaction myTransaction = new MessageQueueTransaction();
//这里使用了委托,当接收消息完成的时候就执行MyReceiveCompleted方法
myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted);
myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.Async.Book) });
myTransaction.Begin();
myQueue.BeginReceive();//启动一个没有超时时限的异步操作
signal.WaitOne();
myTransaction.Commit();
}
}
private static void MyReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
{
try
{
MessageQueue myQueue = (MessageQueue)source;
//完成指定的异步接收操作
Message message = myQueue.EndReceive(asyncResult.AsyncResult);
signal.Set();
Book book = message.Body as Book;
Console.WriteLine("图书编号:{0}--图书名称:{1}--图书作者:{2}--图书定价:{3}",
book.BookId.ToString(),
book.BookName,
book.BookAuthor,
book.BookPrice.ToString());
myQueue.BeginReceive();
}
catch (MessageQueueException me)
{
Console.WriteLine("异步接收出错,原因:" + me.Message);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -