日期:2014-05-17 浏览次数:21061 次
class Demo {
private ShareState _state;
public Demo() {
}
public Demo(ShareState state) {
this._state = state;
}
public virtual void DoTheJob() { //异步方法.
for(int i = 0; i < 50000; i++) {
//lock(_state) //记住在这里也要同步(一个任务不一定是一个线程).
_state.IncreaseState();
}
}
public static Demo Synchronized(Demo demo) { //同步对象.
if(!demo.IsSynchronized) return new SynchronizationDemo(demo);
return demo;
}
public virtual bool IsSynchronized { //异步属性.
get { return false; }
}
private class SynchronizationDemo : Demo {
private object syncRoot = new object(); //用于同步的对象.
private Demo d;
public override bool IsSynchronized { //同步属性.
get {
return true;
}
}
public override void DoTheJob() { //同步方法.
lock(syncRoot) {
d.DoTheJob();
}
}
public SynchronizationDemo(Demo d) {
this.d = d;
&nbs