object removing bug?

Aug 22, 2011 at 7:41 AM
Edited Aug 22, 2011 at 7:43 AM

I have faced with strange behaviour of IoC framework. The issue is that when I remove some object from the IoC it still able to catch events. The source code to describe this is below:

 

// publisher

class EventPublisher
{
    [EventPublication("TestEvent")]
    public event EventHandler TestEventHandler;

    public void ThrowTestEvent()
    {
        loggerDump.Trace("EventPublisher.ThrowTestEvent");
        if (TestEventHandler != null)
            TestEventHandler(this, null);
    }
}

// subscriber       

class EventSubscriber
{
    static int SubscriberID = 0;
    public int EventCounter;
    public int id;

    protected EventSubscriber()
    {
        id = SubscriberID;
        SubscriberID += 1;

        loggerDump.Trace("EventSubscriber id: {0}", id);
        EventCounter = 0;
    }

    ~EventSubscriber()
    {
        loggerDump.Trace("~EventSubscriber id: {0}", id);
    }

    [EventSubscription("TestEvent", ThreadOption.UserInterface)]
    public void CatchTestEvent(object sender, EventArgs e)
    {
        EventCounter += 1;
        loggerDump.Trace(string.Format("EventSubscriber.CatchTestEvent id: {0} cnt: {1}", id, EventCounter));
    }
}

// test method

1: void Test()
2: {
3:        EventPublisher publisher = RootWorkItem.Services.AddNew<EventPublisher>();
4:    
5:        RootWorkItem.Services.AddNew<EventSubscriber>();
6:        publisher.ThrowTestEvent();
7:
8:        RootWorkItem.Services.Remove<EventSubscriber>();
9:        publisher.ThrowTestEvent();
10:
11:        RootWorkItem.Services.AddNew<EventSubscriber>();
12:        publisher.ThrowTestEvent();
13: }
14:

// logfile output

// lines 3 to 6: first subscriber (id:0) was created, event was sent, it is OK
EventSubscriber id: 0
EventPublisher.ThrowTestEvent
EventSubscriber.CatchTestEvent id: 0 cnt: 1

// lines 8 to 9: first subscriber was removed, event was sent again,
// but removed subscriber still catches event
EventPublisher.ThrowTestEvent
EventSubscriber.CatchTestEvent id: 0 cnt: 2

// lines 11 to 12: second subscriber (id:1) was created, event was sent,
// but removed first subscriber (id:0) still catches event
EventSubscriber id: 1
EventPublisher.ThrowTestEvent
EventSubscriber.CatchTestEvent id: 0 cnt: 3
EventSubscriber.CatchTestEvent id: 1 cnt: 1

// line 14:
~EventSubscriber id: 1
~EventSubscriber id: 0

Is there any way to prevent catching events by removed object?

Coordinator
Aug 22, 2011 at 1:25 PM

Good catch - looks like you found a bug.  I'll migrate this over to the Issue Tracker tab and add a fix in, hopefully, the next code drop.

Coordinator
Aug 22, 2011 at 1:27 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.