?? msgqueue.cs
字號:
?using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace MSMQ.App
{
public class MsgQueue
{
/// <summary>
/// 通過Create方法創建使用指定路徑的新消息隊列
/// </summary>
/// <param name="queuePath"></param>
public static void Createqueue(string queuePath)
{
try
{
if (!MessageQueue.Exists(queuePath))
{
MessageQueue.Create(@".\private$\myQueue");
MessageBox.Show("創建隊列成功!");
}
else
{
MessageBox.Show(queuePath + "已經存在!");
}
}
catch (MessageQueueException e)
{
MessageBox.Show(e.Message);
}
}
/// <summary>
/// 連接消息隊列并發送消息到隊列
/// </summary>
public static bool SendMessage(Book book)
{
bool flag = false;
try
{
//連接到本地的隊列
MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
System.Messaging.Message myMessage = new System.Messaging.Message();
myMessage.Body = book;
myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) });
//發送消息到隊列中
myQueue.Send(myMessage);
flag = true;
}
catch (ArgumentException e)
{
MessageBox.Show(e.Message);
}
return flag;
}
/// <summary>
/// 連接消息隊列并從隊列中接收消息
/// </summary>
public static string ReceiveMessage()
{
//連接到本地隊列
MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) });
try
{
//從隊列中接收消息
System.Messaging.Message myMessage = myQueue.Receive();
Book book = (Book)myMessage.Body; //獲取消息的內容
return string.Format("編號:{0},書名:{1},作者:{2},定價:{3}",
book.BookId,
book.BookName,
book.BookAuthor,
book.BookPrice);
}
catch (MessageQueueException e)
{
MessageBox.Show(e.Message);
}
catch (InvalidCastException e)
{
MessageBox.Show(e.Message);
}
return null;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -