如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
HYPERLINK"http://blog.csdn.net/davyfamer/archive/2007/02/08/1505448.aspx"c#多线程编程笔记2第三部分线程的同步同步的意思是在多线程程序中,为了使两个或多个线程之间,对分配临界资源的分配问题,要如何分配才能使临界资源在为某一线程使用的时候,其它线程不能再使用,这样可以有效地避免死锁与脏数据。脏数据是指两个线程同时使用某一数据,造成这个数据出现不可预知的状态!在C#中,对线程同步的处理有如下几种方法:a)等待事件:当某一事件发生后,再发生另一件事。例子3:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;namespaceConsoleApplication1{publicclassClassCounter{protectedintm_iCounter=0;publicvoidIncrement(){m_iCounter++;}publicintCounter{get{returnm_iCounter;}}}publicclassEventClass{protectedClassCounterm_protectedResource=newClassCounter();protectedManualResetEventm_manualResetEvent=newManualResetEvent(false);//ManualResetEvent(initialState),initialState如果为true,则将初始状态设置为终止;如果为false,则将初始状态设置为非终止。protectedvoidThreadOneMethod(){m_manualResetEvent.WaitOne();//在这里是将入口为ThreadOneMethod的线程设为等待m_protectedResource.Increment();intiValue=m_protectedResource.Counter;System.Console.WriteLine("{Threadone}-Currentvalueofcounter:"+iValue.ToString());}protectedvoidThreadTwoMethod(){intiValue=m_protectedResource.Counter;Console.WriteLine("{Threadtwo}-currentvalueofcounter;"+iValue.ToString());m_manualResetEvent.Set();//激活等待的线程}staticvoidMain(){EventClassexampleClass=newEventClass();ThreadthreadOne=newThread(newThreadStart(exampleClass.ThreadOneMethod));ThreadthreadTwo=newThread(newThreadStart(exampleClass.ThreadTwoMethod));threadOne.Start();//请注意这里,这里是先执行线程1threadTwo.Start();//再执行线程2,那么线程2的值应该比线程1大,但结果相反Console.ReadLine();}}}ManualResetEvent它允许线程之间互相发消息。结果如下: