Of Note: This is more of a curiosity question than anything else.
Given a List<Window>
where each window has an event attached to the Close Event which removes the window from the collection, how could you use delegates / events to defer the execution of the Close Event until the collection has been iterated?
For example:
public class Foo
{
private List<Window> OpenedWindows { get; set; }
public Foo()
{
OpenedWindows = new List<Window>();
}
public void AddWindow( Window win )
{
win.Closed += OnWindowClosed;
OpenedWindows.Add( win );
}
void OnWindowClosed( object sender, EventArgs e )
{
var win = sender as Window;
if( win != null )
{
OpenedWindows.Remove( win );
}
}
void CloseAllWindows()
{
// obviously will not work because we can't
// remove items as we iterate the collection
// (the close event removes the window from the collection)
OpenedWindows.ForEach( x => x.Close() );
// works fine, but would like to know how to do
// this with delegates / events.
while( OpenedWindows.Any() )
{
OpenedWindows[0].Close();
}
}
}
Specifically, within the CloseAllWindows()
method, how could you iterate the collection to call the close event, but defer the event being raised until the collection has been completely iterated?