using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; namespace Mesnac.Communication { public sealed class SocketAsyncEventArgsPool : IDisposable { private Stack pool; private IDictionary busypool; //private string[] keys; public Int32 Count { get { lock (this.pool) { return this.pool.Count; } } } public string[] OnlineUID { get { string[] keys = null; lock (this.busypool) { //busypool.Keys.CopyTo(keys, 0); keys = busypool.Keys.ToArray(); } return keys; } } public Stack Pool { get { return this.pool; } } public IDictionary BusyPool { get { return this.busypool; } } public SocketAsyncEventArgsPool(Int32 capacity) { //keys = new string[capacity]; this.pool = new Stack(capacity); this.busypool = new Dictionary(capacity); } public SocketAsyncEventArgsWithId Pop(string uid) { if (uid == string.Empty || uid == "") return null; SocketAsyncEventArgsWithId si = null; lock (this.pool) { si = this.pool.Pop(); } si.UID = uid; si.State = true; //mark the state of pool is not the initial step busypool.Add(uid, si); return si; } public void Push(SocketAsyncEventArgsWithId item) { if (item == null) throw new ArgumentNullException("SocketAsyncEventArgsWithId对象为空"); if (item.State == true) { if (busypool.Keys.Count != 0) { if (busypool.Keys.Contains(item.UID)) busypool.Remove(item.UID); //else // throw new ArgumentException("SocketAsyncEventWithId不在忙碌队列中"); } else throw new ArgumentException("忙碌队列为空"); } item.UID = "-1"; item.State = false; lock (this.pool) { this.pool.Push(item); } } public SocketAsyncEventArgsWithId FindByUID(string uid) { if (uid == string.Empty || uid == "") return null; SocketAsyncEventArgsWithId si = null; foreach (string key in this.OnlineUID) { if (key == uid) { si = busypool[uid]; break; } } return si; } public bool BusyPoolContains(string uid) { lock (this.busypool) { return busypool.Keys.Contains(uid); } } public void Dispose() { this.pool.Clear(); this.busypool.Clear(); this.pool = null; this.busypool = null; } } }