The event sender gets deleted in the client event handler code

I came across the following situation (C # /. NET is here, but I think this is a common problem):

  • Some of our object types (which are collections) are disposable types (IDisposable in C #, which allows clients to explicitly specify an object that you no longer need, free up all your resources)
  • These collections fire events ("oh my, look, someone just added / deleted / changed an element").
  • When the client collector event handler code is run, this code decides to delete the object that just sent the event (which, semantically, is the right action, for example: now the collection does not contain the object of interest for me anymore, so I will get rid of it).

This, of course, damages the sending facilities.

The current "solution" is to protect (that is, deny) to dispose of when events are triggered:

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
    }
}

code>

As you can see, this is not a real solution, since deleting the event sender is effectively blocked during processing of the event processing code.

Any other solution I could find would be line by line

  • After each event trigger, check whether the deletion (or any other “bad” modification of the object) has occurred in the code of the client’s event handler.
  • Discard the sender code (which can be deeply nested until it reaches the event) in a protective way.

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

Perhaps you have an idea.

Thank you for your attention,

Christian

+3
2

, , .

" ", /, ( Dispose on) / . , .

+1

, , , , ( Begin/End .NET).

: , ( ), , .

0

Source: https://habr.com/ru/post/1720275/


All Articles