C#集合之队列
队列是其元素按照先进先出(FIFO)的方式来处理的集合。
队列使用System.Collections.Generic名称空间中的泛型类Queue<T>实现。在内部,Queue<T>类使用T类型的数组,这类似List<T>(http://www.cnblogs.com/afei-24/p/6824791.html)类型。队列实现ICollection和IEnumerable<T>接口,但没有实现ICollection<T>接口,所以ICollection<T>接口定义的Add()合Remove()方法不能用于队列。
Enqueue()方法在队列的一端添加元素,Dequeue()方法在队列的另一端读取和删除元素。再次调用Dequeue(),会删除队列的下一个元素:
Queue<T>类的方法和属性:
在创建队列时,可以使用与List<T>类似的构造函数,也可以使用构造函数指定容量。
非泛型Queue类的默认构造函数不同,它会创建一个包含32项的空数组
下面用一个例子演示队列,使用一个线程将文档添加到队列中,用另一个线程从队列中读取文档,并处理:
//存储在队列中的元素是Document类型 public class Document { public string Title { get; private set; } public string Content { get; private set; } public Document(string title, string content) { this.Title = title; this.Content = content; } } //DocumentManager类是Queue<Document>外面的一层。用来如何将文档添加到队列和从队列中获取文档 public class DocumentManager { private readonly Queue<Document> documentQueue = new Queue<Document>(); //因为多个线程访问DocumentManager类,所以用lock语句锁定对队列的访问 public void AddDocument(Document doc) { lock (this) { documentQueue.Enqueue(doc); } } public Document GetDocument() { Document doc = null; lock (this) { if (this.IsDocumentAvailable) doc = documentQueue.Dequeue(); } return doc; } public bool IsDocumentAvailable { get { lock (this) { return documentQueue.Count > 0; } } } } //使用ProcessDocuments类在一个单独的任务中读取和删除队列中的文档。 public class ProcessDocuments { //能从外部访问的唯一方法是Start()方法 //在Start()中,实例化一个新任务。创建一个ProcessDocuments对象,调用ProcessDocuments的Run()方法 public static void Start(DocumentManager dm) { Task.Factory.StartNew(new ProcessDocuments(dm).Run); } protected ProcessDocuments(DocumentManager dm) { if (dm == null) throw new ArgumentNullException("dm"); documentManager = dm; } private DocumentManager documentManager; //定义一个无限循环,使用DocumentManager类的IsDocumentAvailable属性确定队列中是否还有文档。 protected void Run() { while (true) { if (documentManager.IsDocumentAvailable) { Document doc = documentManager.GetDocument(); if(doc != null) Console.WriteLine("Processing document {0}", doc.Title); } Thread.Sleep(new Random().Next(20)); } } }
客户端代码
static void Main() { var dm = new DocumentManager(); ProcessDocuments.Start(dm); ProcessDocuments.Start(dm); // Create documents and add them to the DocumentManager for (int i = 0; i < 1000; i++) { Document doc = new Document("Doc " + i.ToString(), "content"); dm.AddDocument(doc); Console.WriteLine("Added document {0}", doc.Title); Thread.Sleep(new Random().Next(20)); } Console.ReadKey(); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析