好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

编写网络通讯都要面对一个问题,就是要把很久不存活的死连接清除,如果不这样做那死连接最终会占用大量内存影响服务运作!在实现过程中一般都会使用ping,pong原理,通过ping,pong来更新连接的时效性,最后通过扫描连接列表来清除掉。虽然这种做法比较简单,但很难抽取出通用性的封装,扫描整个列表复杂度也比较高。以下讲解如何通过lru算法实现一个通用高效的探测超时连接功能类。

什么是lru

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

在c#中如何实现lru

c#并不存在这样的数据结构,不过有一个结构很适合实现lru,这个结构就是linkedlist双向链表,通过以下结构图就容易理解通过linkedlist实现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实现通用高效的超时连接探测,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://HdhCmsTestcnblogs测试数据/smark/p/9950802.html

dy("nrwz");

查看更多关于C#中通过LRU实现通用高效的超时连接探测的详细内容...

  阅读:67次