So I have a class that is basically a manager for 20+ copies of another class. What is the best way of handling the same event fired from each one of them? And is this the best way of unregistering the events? Or should I be using a single EventHandler somehow?
I put together a simple example that basically does what I’m doing in my actual project.
class Manager
{
List<Child> children = new List<Child>();
public Manager()
{
for (int i = 0; i < 10; i++)
{
Childchild = new Child();
child.Done += child_Done;
items.Add(child);
child.DoStuff();
}
}
public void RemoveAll()
{
foreach (Child child in items)
{
child.Done -= child_Done;
}
items.Clear();
}
void child_Done(string sometext)
{
Console.WriteLine("child done: " + sometext);
}
}
class Child
{
public delegate void _Done(string sometext);
public event _Done Done;
public Child()
{
}
public void DoStuff()
{
if (Done != null) { Done("finally!"); }
}
}
The unregistration should be fine – as long as the target instance and method match it will work. I will, however, strongly advise you use a more regular event pattern, with a
sender– then you will know which child is talking. For example:and an: