c#线程的同步

同步的意思是在多线程程序中,为了使两个或多个线程之间,对分配临界资源的分配问题,要如何分配才能使临界资源在为某一线程使用的时候,其它线程不能再使用,这样可以有效地避免死锁与脏数据。脏数据是指两个线程同时使用某一数据,造成这个数据出现不可预知的状态!在C#中,对线程同步的处理有如下几种方法: 等待事件:当某一事件发生后,再发生另一件事。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    public class ClassCounter
    {
        protected int m_iCounter = 0;
        public void Increment()
        {
            m_iCounter++;
        }
        public int Counter
        {
            get
            {
                return m_iCounter;
            }
        }
    }
    public class EventClass
    {
        protected ClassCounter m_protectedResource = new ClassCounter();
        protected ManualResetEvent m_manualResetEvent = new ManualResetEvent(false);//ManualResetEvent(initialState),initialState如果为true,则将初始状态设置为终止;如果为false,则将初始状态设置为非终止。
        protected void ThreadOneMethod()
        {
            m_manualResetEvent.WaitOne();//在这里是将入口为ThreadOneMethod的线程设为等待
            m_protectedResource.Increment();
            int iValue = m_protectedResource.Counter;
            System.Console.WriteLine("{Thread one} - Current value of counter:" + iValue.ToString());
        }
        protected void ThreadTwoMethod()
        {
            int iValue = m_protectedResource.Counter;
            Console.WriteLine("{Thread two}-current value of counter;" + iValue.ToString());
            m_manualResetEvent.Set();//激活等待的线程
        }
        static void Main()
        {
            EventClass exampleClass = new EventClass();

            Thread threadOne = new Thread(new ThreadStart(exampleClass.ThreadOneMethod));
            Thread threadTwo = new Thread(new ThreadStart(exampleClass.ThreadTwoMethod));

            threadOne.Start();//请注意这里,这里是先执行线程1
            threadTwo.Start();//再执行线程2,那么线程2的值应该比线程1大,但结果相反

            Console.ReadLine();
        }
    }
}



ManualResetEvent它允许线程之间互相发消息。

结果如下:

{Thread two}-current value of counter;0
{Thread one} - Current value of counter:1

 

 

 



 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值