日期:2014-05-17 浏览次数:20556 次
using System; using System.Linq; using System.Messaging; namespace MSMQ { public delegate void Deal(string msg); public class DbQueue { public MessageQueue mq; public Deal deal; public ReceiveCompletedEventHandler deal2; public DbQueue() { try { if (MessageQueue.Exists(@".\Private$\DBWrite")) mq = new MessageQueue(@".\Private$\DBWrite"); else mq = MessageQueue.Create(@".\Private$\DBWrite"); } catch (MessageQueueException e) { Console.WriteLine(e.Message); } } public void Send(string msg) { mq.Send(msg); Console.WriteLine("发送消息:" + msg); } public void Receive() { while (true) { while (mq.GetAllMessages().Count() > 0) { Console.Write("共有" + mq.GetAllMessages().Count().ToString() + "条"); //Message msg = mq.Receive(); //同步接收 mq.BeginReceive(); mq.ReceiveCompleted += deal2; //Object obj = msg.Body; //deal(obj.ToString()); } Console.WriteLine("等待中"); } } public void ReadAll() { foreach (Message m in mq) { string result = m.Body.ToString(); Console.WriteLine(result); } } } }
using System; namespace MSMQ { class Program { static void Main(string[] args) { DbQueue q = new DbQueue(); while (true) { Console.Write("输入发送字符串:"); string msg=Console.ReadLine(); q.Send(msg); q.ReadAll(); } Console.ReadKey(); } } }
using System; using MSMQ; using System.Threading; using System.Messaging; namespace MSMQ_receiver { class Program { static void Main(string[] args) { DbQueue db = new DbQueue(); db.deal = new Deal(ConcentDeal); db.deal2 = new ReceiveCompletedEventHandler(MyAsyncReceiver); Thread me = new Thread(new ThreadStart(db.Receive)); me.Start(); //db.ReadAll(); } public static void ConcentDeal(string msg) { Console.WriteLine("处理中……"); Thread.Sleep(new Random().Next(1000)); Console.WriteLine("收到消息:" + msg); } public static void MyAsyncReceiver(object resouce,ReceiveCompletedEventArgs args) { MessageQueue mq=resouce as MessageQueue; Message obj=mq.EndReceive(args.AsyncResult); //就是这里异常了 Console.WriteLine("收到的消息为:"+obj.Body.ToString()); //这里报错:找不到能够读取此消息的格式化程序。 } } }