Concurrentqueue-a queue Cache Design

Source: Internet
Author: User
Using  System;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. Web;  Using  System. Collections. Concurrent;  Namespace  Pdajob. pdaservice. Service {  Public   Class Cachelist <t> { Private   Int Maxsize = 10000  ;  Private   Int Shrinklen = 2000  ;  Private Concurrentqueue <cacheitem <t> _ queue = New Concurrentqueue <cacheitem <t> ();  Public Cachelist ( Int Maxsize,Int  Shrinklen ){  This . Maxsize = Maxsize;  This . Shrinklen = Shrinklen ;}  Public   Void  Add (T item ){  # Region Contract if the value is exceeded If (_ Queue. Count> = Maxsize ){  Lock (This  ){  If (_ Queue. Count> = Maxsize) {cacheitem <T> Outitem;  For ( Int I = 0 ; I <shrinklen; I ++ ) {_ Queue. trydequeue (  Out Outitem );}}}}  # Endregion  _ Queue. enqueue (  New Cacheitem <t> () {DATA = item, addtime = Datetime. Now });}  Public Concurrentqueue <cacheitem <t> Queue {  Get  {  Return  _ Queue ;}}} ///   <Summary>      ///  Cached content  ///   </Summary>      ///   <Typeparam name = "T"> </typeparam>      Public   Class Cacheitem <t> {  Public Datetime addtime { Get ; Set  ;} Public T data { Get ; Set  ;}}} 

View code

In a multi-threaded environment, multiple threads may read queue. Count> maxsize. Although queue is thread safeCodeIt can cause _ queue to be moved empty again, so you need to add lock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.