Skip to content

Instantly share code, notes, and snippets.

@FisherMS
Created September 7, 2016 09:23
Show Gist options
  • Save FisherMS/3689b22b0c4214026c8f38ea5cc3b58c to your computer and use it in GitHub Desktop.
Save FisherMS/3689b22b0c4214026c8f38ea5cc3b58c to your computer and use it in GitHub Desktop.
基于LRU算法的连接检测实现
/// <summary>
/// 基于LRU算法的连接检测
/// </summary>
public class LRUDetect:IDisposable
{
/// <summary>
/// 构建检测器
/// </summary>
/// <param name="timeout">超时时间以毫秒为单位</param>
public LRUDetect(int timeout)
{
mTimeout = timeout;
mTimer = new System.Threading.Timer(OnDetect, null, mTimeout, mTimeout);
}
private int mTimeout;
private System.Threading.Timer mTimer;
private LinkedList<Node> mLinkedList = new LinkedList<Node>();
/// <summary>
/// 更新连接
/// </summary>
/// <param name="connection">连接信息</param>
public void Update(IConnecton connection)
{
lock (this)
{
LinkedListNode<LRUDetect.Node> node = connection.Node;
if (node != null)
{
node.Value.LastActiveTime = Environment.TickCount;
mLinkedList.Remove(node);
mLinkedList.AddFirst(node);
}
else
{
node = mLinkedList.AddFirst(new Node());
node.Value.LastActiveTime = Environment.TickCount;
node.Value.Connection = connection;
connection.Node = node;
}
}
}
/// <summary>
/// 删除连接
/// </summary>
/// <param name="connection">连接信息</param>
public void Delete(IConnecton connection)
{
lock (this)
{
LinkedListNode<LRUDetect.Node> node = connection.Node;
if (node != null)
{
node.Value.Connection = null;
mLinkedList.Remove(node);
}
}
}
private void OnDetect(object state)
{
lock (this)
{
int cutime = Environment.TickCount;
LinkedListNode<Node> last = mLinkedList.Last;
while (last !=null && last.Value.Detect(cutime,mTimeout))
{
last.Value.Connection.TimeOut();
last.Value.Connection = null;
mLinkedList.RemoveLast();
last = mLinkedList.Last;
}
}
}
/// <summary>
/// 连接描述接口
/// </summary>
public interface IConnecton
{
/// <summary>
/// 获取对应在LRU算法中的节点
/// </summary>
LinkedListNode<LRUDetect.Node> Node
{
get;
set;
}
/// <summary>
/// 超时操作,当LRU算法检测到应该连接超时的时候会调用该方法
/// </summary>
void TimeOut();
}
/// <summary>
/// 节点信息
/// </summary>
public class Node
{
/// <summary>
/// 最后活动时间
/// </summary>
public int LastActiveTime;
/// <summary>
/// 相关连接信息
/// </summary>
public IConnecton Connection;
/// <summary>
/// 检测是否过期
/// </summary>
/// <param name="cutime"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public bool Detect(int cutime,int timeout)
{
return Math.Abs(cutime - LastActiveTime) > timeout;
}
}
/// <summary>
/// 释放对象
/// </summary>
public void Dispose()
{
if (mTimer != null)
mTimer.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment