First of all, I will try to minimize the memory size of each individual object. Since you create a huge number of objects, it is likely that many of them have similar properties, which makes them an ideal candidate for a fly. A classic example according to Wikipedia article is word processing:
A classic example of using the flyweight template is a data structure for graphically representing characters in a word processor. It might be desirable to have a glyph object for each character in the document containing its font outline, font metrics, and other formatting data, but this would be hundreds or thousands of bytes for each character. Instead, for each character, there may be a reference to a glyph offset object that is shared by each instance of the same character in the document; only the position of each character (in the document and / or on the page) should be stored inside.
As a second step, I would evaluate the size of one object. I emphasize evaluation in this context, because getting the actual size is not so easy in C # . This estimate can then be used to set the maximum number of N objects that can be safely created without encountering an OutOfMemoryException .
You can use this information by tracking how many objects are (approximately) alive, updating the object counter each time an object is created or destroyed, for example.
class Foo { private static NumberOfInstances = 0; public Foo() { NumberOfInstances++; } ~Foo() { NumberOfInstances--; } }
If the thread safety issue is a problem, this implementation, of course, needs to be clarified a bit.
Edit: As Mike noted in his comment, implementing this through a finalizer can lead to serious performance issues in this context. Therefore, it would be better to implement IDisposable and decrement in the Dispose operation. However, this has the disadvantage that you can forget about deleting the object. However, I doubt that this will be a serious problem in your case.
bigge source share