using System; using System.Collections.Concurrent; using System.Threading; namespace MrWu.RabbitMQ { /// /// 消息池 /// public class MessagePool { private static string m_tag; /// /// 唯一标志头 /// public static string tag { get { return m_tag; } set { m_tag = value + DateTime.Now.Ticks; } } private static long id = 0; /// /// 获取id /// /// public static string GetId() { return tag + Interlocked.Increment(ref id); } static MessagePool() { instance = new MessagePool(); } private MessagePool() { } private static MessagePool instance; /// /// 消息池 /// private readonly ConcurrentQueue msgs = new ConcurrentQueue(); /// /// 获取一个消息 /// /// public static Message GetMessage(string msgid = null) { if (msgid == null) msgid = GetId();//Guid.NewGuid().ToString(); Message msg = null; if (!instance.msgs.TryDequeue(out msg)) msg = new Message(); msg.isFree = false; msg.id = msgid; msg.createTime = Debug.Debug.timevalue; return msg; } /// /// 放入一个消息 /// /// public static void PutMessage(ref Message msg) { if (msg == null) return; msg.Clear(); msg.isFree = true; instance.msgs.Enqueue(msg); msg = null; } } }