资源描述:
《c#并发集合的简单方法》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、计算机交流平台:计算机故障_计算机论坛www.it168bbs.comwyC#并发集合的简单方法微软对C#(4.0)的框架添加了全新的并发编程框架,现在我们也能用C#开发支持并发概念的程序的。在并发编程中最让人烦恼的应该就是如何数据同步:避免脏读和脏写,当然我们可以通过Lock技术来实现,也可以使用微软提供给我们的并发集合,这些集合都提供了TryDo方法。用它们对数据的读/写操作能在TryDo返回True的情况下执行。我们来看看它们吧:IProducerConsumerCollection所有的并发集合都实现了这个接口,TryAdd和TryTa
2、ke分别在读和写的时候判断是否能正常进行,不行则返回false。[csharp]publicinterfaceIProducerConsumerCollection:IEnumerable,ICollection,IEnumerable{voidCopyTo(T[]array,intindex);T[]ToArray();boolTryAdd(Titem);boolTryTake(outTitem);}publicinterfaceIProducerConsumerCollection:IEnumerable,IColl
3、ection,IEnumerable{voidCopyTo(T[]array,intindex);T[]ToArray();boolTryAdd(Titem);boolTryTake(outTitem);}ConcurrentQueue并发队列,队列类型的数据结构。[csharp]publicstaticvoidConcurrentQueueTest(){Parallel.For>(1,10000,()=>{while(strNornalQueue.Count!=26){if(strNornalQueue.Count
4、==0){for(inti=65;i<=90;i++){strNornalQueue.Enqueue(Convert.ToChar(i).ToString());}}}Console.WriteLine("-------------start------------");计算机交流平台:计算机故障_计算机论坛www.it168bbs.comwyreturnstrNornalQueue;},(index,state,head)=>{stringtmp=string.Empty;tmp=head.Dequeue();Console.WriteLin
5、e(string.Format("Theelement'{0}'wassetbythread{1}",tmp,System.Threading.Thread.CurrentThread.ManagedThreadId));head.Enqueue(tmp);returnstrNornalQueue;},(result)=>{Console.WriteLine("-------------end------------------");});Console.WriteLine(string.Format("currentcollectionhas
6、{0}elements,Hasduplicatedata:{1}",strNornalQueue.Count,IsDuplicate(strNornalQueue.GetEnumerator())));foreach(stringiteminstrNornalQueue){Console.WriteLine(item);}}publicstaticvoidConcurrentQueueTest(){Parallel.For>(1,10000,()=>{while(strNornalQueue.Coun
7、t!=26){if(strNornalQueue.Count==0){for(inti=65;i<=90;i++){strNornalQueue.Enqueue(Convert.ToChar(i).ToString());}}}Console.WriteLine("-------------start------------");returnstrNornalQueue;},(index,state,head)=>计算机交流平台:计算机故障_计算机论坛www.it168bbs.comwy{stringtmp=string.Empty;tmp=h
8、ead.Dequeue();Console.WriteLine(string.Format("Theelement'{0}'wassetbythrea