0
\$\begingroup\$

In our c# game we use object pools to store sprites once the Dispose() method gets called.Then when the Sprite.Create method gets called if a sprite is in the pool it gets depooled, cleared and returned.An uncommon but excruciatingly hard to tackle issue arises if some class by mistake is keeping a reference to the disposed objects and starts using/updating/moving it even if it's actually being used for something completely different by that time.

Is this a common issue? I remember calling it "pool object resurrection" but it could just be me giving it a funny name.

If it is a common issue, what is the strategy to find the "broken / resurrection" reference that links an object already "Dispose()d" to another object that could use it even after the item was recycled from the pool? Thank you!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If you're game for a larger refactoring, one good way to defend against this is to change the signature of your "return to pool" function.

Instead of an instance method, make it a static method that takes a ref parameter and nulls it out, so:

mySprite.Dispose();

...becomes:

Sprite.Recycle(ref mySprite);
// variable mySprite now holds the value null
// and any attempt to use it will throw an exception.

This won't defend against something like:

var alias = mySprite;
Sprite.Recycle(ref alias);
// alias is null but mySprite still holds a reference to the recycled sprite.

...but that's a more complex pattern you'd rarely write accidentally.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you for the reply! \$\endgroup\$
    – Matteo
    Jun 16, 2023 at 16:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .