You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
3.5 KiB
C#

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<SocketAsyncEventArgsWithId> pool;
private IDictionary<string, SocketAsyncEventArgsWithId> 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<string>();
}
return keys;
}
}
public Stack<SocketAsyncEventArgsWithId> Pool { get { return this.pool; } }
public IDictionary<string, SocketAsyncEventArgsWithId> BusyPool { get { return this.busypool; } }
public SocketAsyncEventArgsPool(Int32 capacity)
{
//keys = new string[capacity];
this.pool = new Stack<SocketAsyncEventArgsWithId>(capacity);
this.busypool = new Dictionary<string, SocketAsyncEventArgsWithId>(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;
}
}
}