7enderhead
7enderhead

Reputation: 31

Event Sender Gets Disposed In Client's Event Handler Code

I'm facing the following situation (C#/.Net here, but I think it's a general problem):

This of course wreaks havoc upon the sending objects.

The current 'solution' is to safeguard (i.e., disallow) disposing while the events are fired:

private bool m_AllowDisposal;

private void MeFiringEvents()
{
    m_AllowDisposal = false;

    // Fire event
    if (m_MyEventHandlers != null)
    {
        m_MyEventHandlers(...);
    }

    m_AllowDisposal = true;
}

public void IDisposable.Dispose()
{
    if (m_AllowDisposal)
    {
        // Dispose resources, set members to null, etc
    }
}

As you can see, this is no real solution, since disposal for the event's sender is effectively inhibited during client's event handling code.

Any other solution I could come up with would be along the lines

Interestingly, I did not find any useful information on that topic on the net, although it seems like a general showstopper.

Perhaps you have got an idea.

Thanks for your consideration,

Christian

Upvotes: 3

Views: 994

Answers (2)

Jeff Sternal
Jeff Sternal

Reputation: 48623

You might consider a different approach if you just need a single listener that should dispose an object, perhaps a simple callback (implementing the Begin/End pattern in .NET).

Disposing of an event's sender isn't ever semantically appropriate: the object that created the collection (or initiated its creation) should be responsible for disposing of it, not an arbitrary observer.

Upvotes: 0

NT_
NT_

Reputation: 2670

Seems to me that there's a lot of things happening at the same time to keep proper track of.

I would try to separate the "disposal of objects" concern, for example add to-be-disposed items in a queue/disposal manager of some sort which would process (call Dispose on) items in a safer and more well designed/understood and deterministic way. If anything, this should help with debugging the problem.

Upvotes: 1

Related Questions