摘要:最近一个项目需要使用到多线程处理,采摘了一些资料学习以下......
代码:using System; using System.Collections.Generic; using System.Threading.Tasks;
namespace yaohao { /// <summary> /// 此处是个类,需要新建一个form1.cs在按钮呼叫start()方法即可。 /// 输出结果在VS下方的输出列表中,或者使用个小技巧, /// 改项目专案的属性运行输出为【控制台应用程序】运行即可 /// </summary> class TestClass { private static object o = new object(); private static List<Product> _Products { get; set; } // 代码中 创建三个并发线程 来操作_Products 集合 //System.Collections.Generic.List 这个列表在多个线程访问下,不能保证是安全的线程, //所以不能接受并发的请求,我们必须对ADD方法的执行进行串行化 void start() { _Products = new List<Product>(); /*创建任务 t1 t1 执行 数据集合添加操作*/ Task t1 = Task.Factory.StartNew(() => { AddProducts();
});
/*创建任务 t2 t2 执行 数据集合添加操作*/ Task t2 = Task.Factory.StartNew(() => { AddProducts(); });
/*创建任务 t3 t3 执行 数据集合添加操作*/ Task t3 = Task.Factory.StartNew(() => { AddProducts(); });
Task.WaitAll(t1, t2, t3); Console.WriteLine(_Products.Count); Console.ReadLine(); } /*执行集合数据添加操作*/
static void AddProducts() { Parallel.For(0, 1000, (i) => { //此处不加lock并发程序时你会发现结果是2679并不是3000,虽然输出了结果,但是不正确,并且会在运行一次后卡住 //从而证明,C#命名空间:System.Collenctions和System.Collenctions.Generic 下的列表,数组,集合确实不能保证线程安全,确实不能预防并发。 //自C#2.0以来,LOCK是一直存在的。使用LOCK(互斥锁)是可以做到防止并发的 //但是锁的引入,带来了一定的开销和性能的损耗,并降低了程序的扩展性, //而且还会有死锁的发生(虽说概率不大,但也不能不防啊),因此:使用LOCK进行并发编程显然不太适用 //在.NET Framework4.0以后的版本中提供了命名空间:System.Collections.Concurrent 来解决线程安全问题,通过这个命名空间,能访问以下为并发做好了准备的集合。 //1.BlockingCollection 与经典的阻塞队列数据结构类似,能够适用于多个任务添加和删除数据,提供阻塞和限界能力。 //2.ConcurrentBag 提供对象的线程安全的无序集合 //3.ConcurrentDictionary 提供可有多个线程同时访问的键值对的线程安全集合 //4.ConcurrentQueue 提供线程安全的先进先出集合 //5.ConcurrentStack 提供线程安全的后进先出集合 //这些集合通过使用比较并交换和内存屏障等技术,避免使用典型的互斥重量级的锁,从而保证线程安全和性能。 //ConcurrentQueue //ConcurrentQueue 是完全无锁的,能够支持并发的添加元素,先进先出。 //lock (o) //{ Product product = new Product(); product.Name = "name" + i; product.Category = "Category" + i; product.SellPrice = i; _Products.Add(product);
//} }); }
class Product { public string Name { get; set; } public string Category { get; set; } public int SellPrice { get; set; } }
} } |
|
参考文章:
C#并行与多线程
https://blog.csdn.net/weixin_39712611/article/details/110705201