//-----------------------------------------------------------------------
|
// <copyright file="MSMQHelper.cs" company="iPilotWhale">
|
// Suzhou Linktron Systems Co.,Ltd . All rights reserved.
|
// </copyright>
|
// <author>温向超</author>
|
// <description>消息队列操作辅助类</description>
|
//-----------------------------------------------------------------------
|
using System;
|
using System.Messaging;
|
|
namespace HMI.Core.Util
|
{
|
/// <summary>
|
/// 消息队列操作类
|
/// </summary>
|
public class MSMQHelperCCC
|
{
|
/// <summary>
|
/// 消息队列名称
|
/// </summary>
|
private string msmqName = string.Empty;
|
|
/// <summary>
|
/// 消息队列路径
|
/// </summary>
|
private string msmqPath = string.Empty;
|
|
/// <summary>
|
/// 要操作的消息队列
|
/// </summary>
|
private MessageQueue msgQueue = null;
|
|
/// <summary>
|
/// 构造函数
|
/// </summary>
|
/// <param name="Name">消息队列名称</param>
|
public MSMQHelperCCC(string Name)
|
{
|
try
|
{
|
this.msmqName = Name;
|
this.msmqPath = ".\\private$\\" + this.msmqName;
|
if (MessageQueue.Exists(this.msmqPath))
|
{
|
// 如果当前消息队列已经存在
|
this.msgQueue = new MessageQueue(this.msmqPath);
|
}
|
else
|
{
|
// 如果消息队列不存在,则创建消息对垒
|
this.msgQueue = MessageQueue.Create(this.msmqPath);
|
}
|
this.msgQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
|
}
|
catch(Exception ex)
|
{
|
throw new Exception(ex.Message);
|
}
|
}
|
|
/// <summary>
|
/// 发送消息
|
/// </summary>
|
/// <param name="MessageID">消息ID</param>
|
/// <param name="MsgString">要发送的字符串</param>
|
public void Send(string MessageID,string MsgString)
|
{
|
try
|
{
|
this.msgQueue.Send(MsgString, MessageID);
|
}
|
catch(Exception ex)
|
{
|
throw new Exception(ex.Message);
|
}
|
}
|
|
/// <summary>
|
/// 接收消息队列中的消息
|
/// </summary>
|
/// <param name="TimeOut">超时时间(ms)</param>
|
/// <param name="MessageID">消息ID</param>
|
/// <param name="MsgString">消息内容</param>
|
public void Receive(long TimeOut,out string MessageID,out string MsgString)
|
{
|
try
|
{
|
MessageID = string.Empty;
|
MsgString = string.Empty;
|
TimeSpan Time = new TimeSpan(TimeOut);
|
Message MsgReceived = null;
|
try
|
{
|
MsgReceived = this.msgQueue.Receive(Time);
|
}
|
catch
|
{
|
// do nothing
|
}
|
|
if(MsgReceived!=null)
|
{
|
MessageID = MsgReceived.Label;
|
MsgString = MsgReceived.Body.ToString();
|
}
|
}
|
catch(Exception ex)
|
{
|
throw new Exception("接收消息失败:" + ex.Message);
|
}
|
}
|
|
/// <summary>
|
/// 清除消息队列中的消息
|
/// </summary>
|
public void Clear()
|
{
|
try
|
{
|
this.msgQueue.Purge();
|
}
|
catch(Exception ex)
|
{
|
throw new Exception("清除消息队列失败:" + ex.Message);
|
}
|
}
|
|
/// <summary>
|
/// 关闭当前队列
|
/// </summary>
|
public void Close()
|
{
|
this.msgQueue.Close();
|
}
|
|
/// <summary>
|
/// 删除当前队列
|
/// </summary>
|
public void Delete()
|
{
|
MessageQueue.Delete(this.msmqPath);
|
}
|
}
|
}
|