R
Rhy Mednick
I have a class (let's call it ClassA) that I've written which has events.
In another class (let's call it ClassB) I create a collection of ClassA
objects. In a third class (ClassC) I create a reference to some of the
ClassA objects created in ClassB. In ClassC I hook into the ClassA events
with a foreach loop so that I hook each object. The code is something like
this:
class ClassC {
void SomeMethod()
{
foreach (ClassA item in ClassACollection)
{
item.MyEvent += new EventHandler(item_MyEvent);
}
}
}
Objects of type ClassC keep getting created and deleted, but the objects of
ClassA that it references stay in memory. Therefore, every time I load a
new instance of ClassC the event gets hooked again. What I'm seeing is that
I fire the event once but I end up getting it raised in the code that
responds to it (item_MyEvent method) for every time it was added when I only
want it to get caught once.
How can I be sure that I only add the handler to the event once for each
item? Since the code is in ClassC it's not allowed to inspect the
ClassA.MyEvent to see if something's already hooked to it.
I hope this makes sense. Creating a repro case wouldn't make sense here
because it's my application logic that's causing the problem.
Thanks.
In another class (let's call it ClassB) I create a collection of ClassA
objects. In a third class (ClassC) I create a reference to some of the
ClassA objects created in ClassB. In ClassC I hook into the ClassA events
with a foreach loop so that I hook each object. The code is something like
this:
class ClassC {
void SomeMethod()
{
foreach (ClassA item in ClassACollection)
{
item.MyEvent += new EventHandler(item_MyEvent);
}
}
}
Objects of type ClassC keep getting created and deleted, but the objects of
ClassA that it references stay in memory. Therefore, every time I load a
new instance of ClassC the event gets hooked again. What I'm seeing is that
I fire the event once but I end up getting it raised in the code that
responds to it (item_MyEvent method) for every time it was added when I only
want it to get caught once.
How can I be sure that I only add the handler to the event once for each
item? Since the code is in ClassC it's not allowed to inspect the
ClassA.MyEvent to see if something's already hooked to it.
I hope this makes sense. Creating a repro case wouldn't make sense here
because it's my application logic that's causing the problem.
Thanks.