我修改了枚举集合,但是,我在它周围加了锁……它不明白为什么我得到“集合已修改;枚举操作可能无法执行”。我不想解决它:“foreach(_observers.ToList()中的IObserver obs)”
代码是观察者模式:
class Program
{
static void Main(string[] args)
{
Subject sub = new Subject();
Obs1 obs1 = new Obs1(sub);
Obs2 obs2 = new Obs2(sub);
sub.Nodefiy();
sub.Nodefiy();
sub.Nodefiy();
sub.Nodefiy();
sub.Nodefiy();
sub.Nodefiy();
Console.ReadKey();
}
}
public interface IObserver
{
void Update(int data);
}
public interface ISubscrib
{
void Reg(IObserver obs);
void UnReg(IObserver obs);
void Nodefiy();
}
public class Subject : ISubscrib
{
private static Object _lock;
private List<IObserver> _observers;
private int data = 0;
public Subject()
{
_lock = new Object();
_observers = new List<IObserver>();
}
public void Reg(IObserver obs)
{
lock (_lock)
{
_observers.Add(obs);
}
}
public void UnReg(IObserver obs)
{
lock (_lock)
{
int ind = _observers.IndexOf(obs);
if (ind >= 0)
{
_observers.RemoveAt(ind);
}
}
}
public void Nodefiy()
{
data = data + 1;
lock (_lock)
{
int sentData = data;
//foreach (IObserver obs in _observers.ToList<IObserver>())
foreach (IObserver obs in _observers)
{
obs.Update(sentData);
}
}
}
}
public class Obs1 : IObserver
{
private ISubscrib _subj;
public Obs1(ISubscrib subj)
{
_subj = subj;
_subj.Reg(this);
}
public void Update(int data)
{
Console.WriteLine("Obs1: {0}", data);
}
}
public class Obs2 : IObserver
{
private ISubscrib _subj;
public Obs2(ISubscrib subj)
{
_subj = subj;
_subj.Reg(this);
}
public void Update(int data)
{
Console.WriteLine("Obs2: {0}", data);
if (data > 3)
{
_subj.UnReg(this);
}
}
}
谁能帮我?谢谢...