using System;
|
using System.Messaging;
|
|
namespace HMI.Simple.Util
|
{
|
|
public class MQAlarm
|
{
|
public string Source { get; set; }
|
public string Content { get; set; }
|
public int Level { get; set; }
|
}
|
|
|
public class MSMQHelper : IDisposable
|
{
|
/// <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 MSMQHelper(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(MQAlarm) });
|
}
|
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 source, string MsgString, int level)
|
{
|
try
|
{
|
this.msgQueue.Send(new MQAlarm { Source = source, Content = MsgString, Level = level }, 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 MQAlarm alarm)
|
{
|
try
|
{
|
MessageID = string.Empty;
|
alarm = null;
|
TimeSpan Time = new TimeSpan(TimeOut);
|
Message MsgReceived = null;
|
try
|
{
|
MsgReceived = this.msgQueue.Receive(Time);
|
}
|
catch
|
{
|
// do nothing
|
}
|
|
if (MsgReceived != null)
|
{
|
MessageID = MsgReceived.Label;
|
alarm = (MQAlarm)MsgReceived.Body;
|
}
|
}
|
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);
|
}
|
|
public void Dispose()
|
{
|
this.Close();
|
}
|
}
|
}
|