C#-----线程安全的ConcurrentQueue队列

   ConcurrentQueue队列是一个高效的线程安全的队列,是.Net Framework 4.0,System.Collections.Concurrent命名空间下的一个数据结构

  • IsEmpty  获取一个值,判断是否为空
  • Count  获取包含的元素数
  • Enqueue(T item)  将对象添加到队列的结尾处
  • TryDequeue(out T result)  尝试移除并返回并发队列开头处的对象
  • TryPeek(out T result)  尝试返回开头处的对象但不将其移除
  • ElementAt(int index)  返回序列中的指定索引处的元素
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestConcurrentQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            //ConcurrentQueue 表示线程安全的先进先出 (FIFO) 集合
            ConcurrentQueue currendQueue = new ConcurrentQueue();
            Employee empOne = new Employee("王晶", "", 20, "市场部");
            Employee empTwo = new Employee("陈浩民", "", 24, "技术部");
            Employee empThree = new Employee("王诗玲", "", 25, "市场部");
            //Enqueue(T item) 将对象添加到结尾处
            currendQueue.Enqueue(empOne);
            currendQueue.Enqueue(empTwo);
            currendQueue.Enqueue(empThree);

            //获取包含的元素数
            if (currendQueue.Count > 0)
            {
                //TryDequeue(out T result) 尝试移除并返回并发队列开头处的对象
                currendQueue.TryDequeue(out Employee employee);
                Console.WriteLine(employee);

                if (currendQueue.Count > 0)
                {
                    for (int i = 0; i < currendQueue.Count; i++)
                    {
                        Employee emp = currendQueue.ElementAt(i);
                        Console.WriteLine(emp);
                    }
                }
            }
        }
    }

    /// 
    /// 雇员类
    /// 
    class Employee
    {
        /// 
        /// 雇员姓名
        /// 
        public string EmpName { get; set; }
        /// 
        /// 雇员性别
        /// 
        public string EmpSex { get; set; }
        /// 
        /// 雇员年龄
        /// 
        public int EmpAge { get; set; }
        /// 
        /// 雇员部门
        /// 
        public string DeptName { get; set; }
        /// 
        /// 构造函数
        /// 
        /// 
        /// 
        /// 
        /// 
        public Employee(string empName, string empSex, int empAge, string deptName)
        {
            EmpName = empName;
            EmpSex = empSex;
            EmpAge = empAge;
            DeptName = deptName;
        }

        public override string ToString()
        {
            return "Employee[EmpName=" + EmpName + ",EmpSex=" + EmpSex + ",EmpAge=" + EmpAge + ",DeptName=" + DeptName + "]";
        }
    }
}

 

转载于:https://www.cnblogs.com/fengfuwanliu/p/10642191.html

你可能感兴趣的:(C#-----线程安全的ConcurrentQueue队列)