Queue And ConcurrentQueue in .NET

本文通过两个示例介绍了C#中ConcurrentQueue(非阻塞队列)和Queue(阻塞队列)的基本用法。ConcurrentQueue支持多线程并发访问而不会发生数据竞争,而Queue则不支持这种操作。文章展示了如何创建和初始化队列、遍历队列元素等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列分为阻塞队列和非阻塞队列,今天在优快云上看到了两个Demo,摘录如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections.Concurrent;
using System.Threading;
using System.Collections;

namespace ConcurrentQueueDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region ConcurrentQueue
            // Construct a ConcurrentQueue.
            ConcurrentQueue<int> cq = new ConcurrentQueue<int>();

            // Populate the queue.
            for (int i = 0; i < 10000; i++) cq.Enqueue(i);

            // Peek at the first element.
            int result;
            if (!cq.TryPeek(out result))
            {
                Console.WriteLine("CQ: TryPeek failed when it should have succeeded");
            }
            else if (result != 0)
            {
                Console.WriteLine("CQ: Expected TryPeek result of 0, got {0}", result);
            }

            int outerSum = 0;
            // An action to consume the ConcurrentQueue.
            Action action = () =>
            {
                int localSum = 0;
                int localValue;
                while (cq.TryDequeue(out localValue)) localSum += localValue;
                Interlocked.Add(ref outerSum, localSum);
            };

            // Start 4 concurrent consuming actions.
            Parallel.Invoke(action, action, action, action);

            Console.WriteLine("outerSum = {0}, should be 49995000", outerSum);

            #endregion
            
            #region
            // Creates and initializes a new Queue.
            Queue myQ = new Queue();
            myQ.Enqueue("Hello");
            myQ.Enqueue("World");
            myQ.Enqueue("!");

            // Displays the properties and values of the Queue.
            Console.WriteLine("myQ");
            Console.WriteLine("\tCount:    {0}", myQ.Count);
            Console.Write("\tValues:");
            PrintValues(myQ);
            #endregion

            Console.ReadKey();
        }

        public static void PrintValues(IEnumerable myCollection)
        {
            foreach (var obj in myCollection)
                Console.Write("    {0}", obj);
            Console.WriteLine();
        }
    }
}
代码相信大家都能看得懂,不在赘述!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值