internal class SaeQueuePool { /// <summary> /// SocketAsyncEventArgs可复用队列 /// </summary> private readonly ConcurrentQueue<SocketAsyncEventArgs> _saeQueue; /// <summary> /// 获取队列中的数量 /// </summary> public int Count => _saeQueue.Count; /// <summary> /// 构造函数 /// </summary> public SaeQueuePool(int count) { _saeQueue = new ConcurrentQueue<SocketAsyncEventArgs>(); for (var i = 0; i < count; i++) { _saeQueue.Enqueue(new SocketAsyncEventArgs()); } } /// <summary> /// 取出项 /// </summary> public Task<SocketAsyncEventArgs> Dequeue() { return Task.Run(() => { try { var success = _saeQueue.TryDequeue(out var item); if (!success) item = new SocketAsyncEventArgs(); item.Completed += Item_Completed; return item; } catch (System.Exception) { return null; } }); } /// <summary> /// /// </summary> private void Item_Completed(object sender, SocketAsyncEventArgs e) { e.Completed -= Item_Completed; _saeQueue.Enqueue(e); } /// <summary> /// 退回项到池中 /// </summary> public void Enqueue(SocketAsyncEventArgs sae) { sae.Completed -= Item_Completed; _saeQueue.Enqueue(sae); } }