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. 太牛了,结贴!!!
先说 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 是不相符的。
是事件注册,和你说的+1什么的貌似不是一回事吧,注册的时候,真正追到委托那是有个链表的吧,同时注册不就是在这个链表上加值么,有没有什么像事物一样,必须一致的操作,干吗要lock呢?
ps:大神很牛,膜拜~!
就是你的这个在 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
加了lock,就可以在别的线程注册时,注册不了,而保持已经注册了的事件的解决方法是对的。
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. 太牛了,结贴!!!