abstract class Foo
{
private List<Object> container;
private bool update;
Foo Foo()
{
container = new List<object>();
update = false;
}
public abstract Bar CreateBar();
public void BeginUpdate()
{
if (!update)
{
Thread update_thread = new Thread(new ThreadStart(Update));
update_thread.Start();
}
}
private void Update()
{
update = true;
while (update)
{
lock (container)
{
if (...)
container.Add(this.CreateBar());
else
container.Remove(...);
}
Thread.Sleep(1337);
}
}
public void EndUpdate()
{
update = false;
}
public List<Object> Objects
{
get
{
lock (container)
{
return this.container;
}
}
}
}
When something outside of Foo calls the Foo's Object accessor like,
List<Objects> objects = foo_instance.Objects;
foreach (Object o in objects)
{
Thread.Sleep(31173);
}
How will the locking occur? Will the thread running Update() have to wait until the above foreach is done processing objects list? I would like that these two would work simultaneously, is the only solution to make a deep copy of objects?