c#多线程编程笔记5(完结)

c#多线程编程笔记5(完结)

ID:41037150

大小:71.50 KB

页数:11页

时间:2019-08-14

c#多线程编程笔记5(完结)_第1页
c#多线程编程笔记5(完结)_第2页
c#多线程编程笔记5(完结)_第3页
c#多线程编程笔记5(完结)_第4页
c#多线程编程笔记5(完结)_第5页
资源描述:

《c#多线程编程笔记5(完结)》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

1、c#多线程编程笔记5(完结)a)       使用InterLocked类InterLocked使用于递增、递减以及更改变量值这类较为简单的操作。如果所有的任务都是在同步上下文中的一些简单操作,那么InterLocked类作为一个非常便捷的方法,可以大大减少需要编写的代码量。笔者没有在如下的试例程序中没有感觉到它的功用,当然也不排除笔者技术有限未能理解到设计者的心思。例子8:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading; namespaceCo

2、nsoleApplication1{publicclassInterLocked8{publicstaticinti=0; publicvoidMethod1(){if(i<20){Interlocked.Increment(refi);}else{Interlocked.Decrement(refi);}Thread.Sleep(500);Console.WriteLine("Currentthreadis{0},thevalueofiis{1}",Thread.CurrentThread.Name,i);}}classMainEntryPoint1{publ

3、icstaticvoidMain(){ThreadmyThread;InterLocked8il8=newInterLocked8();for(intn=0;n<20;n++){myThread=newThread(newThreadStart(il8.Method1));myThread.Name=String.Format("Thread{0}",n);myThread.Start();}Console.ReadLine();}}}b)      无等待读取当一个线程处在更改变量值的过程中,另一个线程也要更改该变量的值或需要读取变量值,就会出现同步的问题,前

4、文中已介绍了这些同步技术都用当一个线程执行受保护的代码部分时,就会阻塞其它线程对这部分的操作。但如果所有的线程都只读取这个资源,而不改变它的时候,这样做其实是没有必要与浪费时间的。在。NET中用无等待读取来提供这方面的功能。例子9:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;namespaceConsoleApplication1{publicclassReaderWriterClass{protectedReaderWriterLockm_

5、readerLock=newReaderWriterLock();protectedintm_counter=0;protectedintm_readerBlocks=0;protectedintm_writerBlocks=0; protectedvoidThreadOneMethod(){for(inti=0;i<200;i++){try{m_readerLock.AcquireReaderLock(0);try{System.Console.WriteLine(m_counter);}finally{m_readerLock.ReleaseReaderLo

6、ck();}}catch(Exception){Interlocked.Increment(refm_readerBlocks);}}}protectedvoidThreadTwoMethod(){for(inti=0;i<100;i++){try{m_readerLock.AcquireWriterLock(0);try{Interlocked.Increment(refm_counter);}finally{m_readerLock.ReleaseWriterLock();}}catch(Exception){Interlocked.Increment(re

7、fm_writerBlocks);}Thread.Sleep(1);}} publicintReaderBlocks{get{returnm_readerBlocks;}} publicintWriteerBlocks{get{returnm_writerBlocks;}} staticvoidMain(){ReaderWriterClassexampleClass=newReaderWriterClass();ThreadthreadOne=newThread(newThreadStart(exampleClass.ThreadOneMethod));Thre

8、adthreadTwo=

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。