using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
private static object o = new object();
private static Queue<Product> _ProductsNormal { get; set; }
private static Queue<Product> _Products { get; set; }
private static ConcurrentQueue<Product> _ConcurrenProducts { get; set; }
/* -------------------------------------------
* 对比lock锁和ConcurrentQueue并发性能
* -------------------------------------------
在.NET Framework4.0以后的版本中提供了命名空间:System.Collections.Concurrent 来解决线程安全和lock锁性能问题,通过这个命名空间,能访问以下为并发做好了准备的集合。
1.BlockingCollection 与经典的阻塞队列数据结构类似,能够适用于多个任务添加和删除数据,提供阻塞和限界能力。
2.ConcurrentBag 提供对象的线程安全的无序集合
3.ConcurrentDictionary 提供可有多个线程同时访问的键值对的线程安全集合
4.ConcurrentQueue 提供线程安全的先进先出集合
5.ConcurrentStack 提供线程安全的后进先出集合
这些集合通过使用比较并交换和内存屏障等技术,避免使用典型的互斥重量级的锁,从而保证线程安全和性能。
*/
static void Main(string[] args)
{
#region 不启用并行计算使用锁lock
//休眠重置校准结果
Thread.Sleep(1000);
_ProductsNormal = new Queue<Product>();
Stopwatch swTaskn = new Stopwatch();//用于统计时间消耗的
swTaskn.Start();
Task tn1 = Task.Factory.StartNew(() => { AddProductsNormal(); });
Task tn2 = Task.Fact
C# 使用Parallel并行对比lock锁和ConcurrentQueue并发性能
最新推荐文章于 2024-06-22 12:29:36 发布