怎么在C#中通过LRU实现通用高效的超时连接探测

发布时间:2021-06-01 17:07:43 作者:Leah
来源:亿速云 阅读:138

今天就跟大家聊聊有关怎么在C#中通过LRU实现通用高效的超时连接探测,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

什么是LRU

在这里还是要大概介绍一下LRU,LRU算法的设计原则是:如果一个数据在最近一段时间没有被访问到,那么在将来它被访问的可能性也很小.也就是说,当限定的空间已存满数据时,应当把最久没有被访问到的数据淘汰.当然在这里并不需要使用到自动淘汰机制,只需要把未位到达超时的连接清除即可。

在C#中如何实现LRU

C#并不存在这样的数据结构,不过有一个结构很适合实现LRU,这个结构就是LinkedList双向链表,通过以下结构图就容易理解通过LinkedList实现LRU

怎么在C#中通过LRU实现通用高效的超时连接探测

通过LinkedList的功能我们可以把活越项先移出来,然后再把项移到头部。在这里需要注意LinkedList的Remove方法,它有两个重载版本,两个版本的复杂度不一样。一个是O(n)一个是O(1)所以使用上一定要注意,否则在数据多的情况下效率差别巨大(这些细节都可以通过源代码来查看)!

代码实现

前面已经大概讲述的原理,接下来要做的就是代码实现了。第一步需要制订一个基础可控测对象规则接口,这样就可以让现有的已经实现的功能实现它并可得到相关功能的支持。

public interface IDetector
  {
    double ActiveTime
    { get; set; }
    LinkedListNode<IDetector> DetectorNode
    {
      get;
      set;
    }
  }

接口定义了两个属性,一个是最近活越时间,另一个就是LinkedListNode<IDetector>这个属性比交关键,通过LinkedListNode<IDetector>可以让LinkedList在Remove时复杂度为O(1).接下来就要针对基于LRU算法处理超时制定一个应用规则

 public interface ILRUDetector
  {
    void Update(IDetector item);
    void Detection(int timeout);
    double GetTime();
    Action<IList<IDetector>> Timeout { get; set; }
  }

规则也是比较简单,Update用于更新跟踪对象,一般在处理接受ping或pong包后进行调用;Detection方法是探测超出指定时间的对象,时间当位是毫秒,如果存在有超时的对象则触发Timeout事件;GetTime是获取探测器已经运行的时间单位毫秒!规则定好了那接着要做的事实就是要实现它:

 class LRUDetector : ILRUDetector, IDisposable
  {
    public LRUDetector()
    {
      mTimeWatch = new System.Diagnostics.Stopwatch();
      mTimeWatch.Restart();
    }
    private Buffers.XSpinLock xSpinLock = new Buffers.XSpinLock();
    private System.Diagnostics.Stopwatch mTimeWatch;
    private LinkedList<IDetector> mItems = new LinkedList<IDetector>();
    public Action<IList<IDetector>> Timeout
    {
      get; set;
    }
    public void Detection(int timeout)
    {
      double time = GetTime();
      List<IDetector> result = new List<IDetector>();
      using (xSpinLock.Enter())
      {
        LinkedListNode<IDetector> last = mItems.Last;
        while (last != null && (time - last.Value.ActiveTime) > timeout)
        {
          mItems.Remove(last);
          result.Add(last.Value);
          last.Value.DetectorNode = null;
          last = mItems.Last;
        }
      }
      if (Timeout != null && result.Count > 0)
        Timeout(result);
    }
    public void Update(IDetector item)
    {
      using (xSpinLock.Enter())
      {
        if (item.DetectorNode == null)
          item.DetectorNode = new LinkedListNode<IDetector>(item);
        item.ActiveTime = GetTime();
        if (item.DetectorNode.List == mItems)
          mItems.Remove(item.DetectorNode);
        mItems.AddFirst(item);
      }
    }
    public void Dispose()
    {
      mItems.Clear();
    }
    public double GetTime()
    {
      return mTimeWatch.Elapsed.TotalMilliseconds;
    }
  }

代码并不复杂,相信不用过多解释也能看懂相关操作原理。

测试

既然功能已经实现,接下来就要对代码进行测试看运行效果。测试代码比较简单首先开启一个Timer定时执行Detection,另外开一个线程去调用Update方法

class Program
  {
    public class TestDetector : IDetector
    {
      public double ActiveTime { get; set; }
      public string Name { get; set; }
      public LinkedListNode<IDetector> DetectorNode { get; set; }
    }
    static void Main(string[] args)
    {
      LRUDetector lRUDetector = new LRUDetector();
      lRUDetector.Timeout = (items) =>
      {
        foreach (TestDetector item in items)
          Console.WriteLine($"{(item.Name)} timeout {lRUDetector.GetTime() - item.ActiveTime}ms");
      };
      System.Threading.Timer timer = null;
      timer = new System.Threading.Timer(o =>
      {
        timer.Change(-1, -1);
        lRUDetector.Detection(5000);
        timer.Change(5000, 5000);
      }, null, 5000, 5000);
      System.Threading.ThreadPool.QueueUserWorkItem(o =>
      {
        int i = 0;
        while (true)
        {
          System.Threading.Thread.Sleep(500);
          i++;
          TestDetector testDetector = new TestDetector();
          testDetector.Name = "my name is " + i;
          lRUDetector.Update(testDetector);
        }
      });
      Console.Read();
    }
  }

运行效果:

怎么在C#中通过LRU实现通用高效的超时连接探测

看完上述内容,你们对怎么在C#中通过LRU实现通用高效的超时连接探测有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. c#如何实现哈希表线性探测
  2. 通过C#查询SQLServer数据库超时

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

lru

上一篇:怎么在易语言中通过post操作的小米路由器

下一篇:怎么在Go中实现并发控制context

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》