本帖最后由 yuandonghuia 于 2012-03-21 08:55:56 编辑

解决方案 »

  1.   

    防止变量被其他线程同时修改,保证变量的稳定,你还是看看lock的帮助和线程的锁机制吧
      

  2.   

    为什么这里要加他呢?为什么这里会涉及到多线程呢?还有为何他要定义一个毫不相关的object呢?大概的意思我也明白,我就想知道详细一些,我怕会给我搞的框架以后的稳定性带来隐患~
      

  3.   

    关注下,object就是用于lock判断的,保证object同时只能被一个线程访问,感觉像flag标志位一样
      

  4.   

    在多线程的时候可能有多个线程同时注册,要不lock可能会丢失的吧
      

  5.   

    我又重新看了看lock的定义,object那块明白了,但是这里为什么具体要这样用还是有点疑惑,可能是对整体的C#.net里面的流程不大明白吧。还有我想知道,如果我不加lock,当两个线程同时注册事件的时候,能发生什么冲突。
      

  6.   

    我估计编译成IL之后,你要是不Lock,几个事件会被注册到同一个内存地址,这就导致了冲突,原理应该和Singleton 模式差不多吧
      

  7.   

    这说起来就话长了,
    先说 a+=1,这个操作在多线程中是不安全的,楼主,你理解了这个,就什么都好说了。
    a+=1其实是两步操作 先把a的值取出来,然后+1,然后再写回a里面去
    假设初始a = 0;
    线程1 a+=1.线程2 a+=1,
    线程1,先把a的值取出来,+1,这时切换到了线程2.线程2把a的值取出来,+1,然后线程1,线程2分别把值写回去。最后的结果就是a == 1,很明显这和你预期的 a == 2 是不相符的。
      

  8.   

     _mye += value;
    是事件注册,和你说的+1什么的貌似不是一回事吧,注册的时候,真正追到委托那是有个链表的吧,同时注册不就是在这个链表上加值么,有没有什么像事物一样,必须一致的操作,干吗要lock呢?
      

  9.   

    原理是这样的啊?过程是先在内存中申请一个新地址,将a地址的值复制到新地址中,再在新地址中做加法,最后在把新地址中的值写入到a的地址中?对吧。值类型的“+=”都是这么操作?引用类型的“+=”是怎么个步骤呢?
    ps:大神很牛,膜拜~!
      

  10.   


    就是你的这个在 c# 4.0 以前 需要 lock  以后不需要
    public class Shape : IDrawingObject, IShape
    {
        // Create an event for each interface event
        event EventHandler PreDrawEvent;
        event EventHandler PostDrawEvent;    event EventHandler IDrawingObject.OnDraw
        {
            add { PreDrawEvent += value; }
            remove { PreDrawEvent -= value; }
        }
    }
    参考http://www.abhisheksur.com/2010/06/c-40-features.html
      

  11.   

    如果多个线程都用了同一个资源进行了注册,那这个事件的注册会是最后一个。
    加了lock,就可以在别的线程注册时,注册不了,而保持已经注册了的事件的解决方法是对的。
      

  12.   

    Event Object LockingIf you know what happens when you try to add an EventHandler or try to remove one event handler from an Event Accessor or even a public event you might know, the compiler places an explicit object lock when the event are added or removed. This is something like lock(this). It is always better to avoid lock(this) as say you are using multiple threads accessing same object. If you invoke lock(this) it means the object will be locked to all other threads even though another thread tries to access another portion of the code.  In case of C# less than 4.0, the compiler invokes explicit lock on the object when you want to add or remove a EventHandler from code. So it will look like:private event EventHandler _myevent;
     public event EventHandler MyEvent
     {
         add { lock (this) { this._myevent += value; } }
         remove { lock (this) { this._myevent -= value; } }
     }Now if you see the event accessor for the event you will see _myevent accessor is almost similar to what i wrote for MyEvent accessor.
     MethodImpl(MethodImplOptions.Synchronized)] attribute makes the object locked whenever the call to add event or remove event is made. This looks worse.   太牛了,结贴!!!