This object is in archive! 

[ModAPI] Whitelist WeakReference and ConditionalWeakTable

Bauke Conijn shared this feedback 22 months ago
Not Enough Votes

Please add the following two classes to the ModAPI whitelist:


System.Runtime.CompilerServices.ConditionalWeakTable
System.WeakReference

When writing mods, it's occasionally needed to add fields to existing classes. As the classes themselves cannot be modified, a common solution is to create a dictionary, mapping each object to another object containing the additional fields. For example, in the buildinfo mod:

Dictionary<IMyTerminalAction, ActionWrapper> ActionWrappers
However, this dictionary will now accumulate a reference to every MyTerminalAction ever created. So the garbage collector will not remove them and you've created a memory leak. That would not be an issue if there's a maximum number of actions that will ever be created during a game, but the ModAPI allows creating actions dynamically.


This is a common issue in garbage collected languages such as C# and cannot be fixed without support from the garbage collector. However, this is such a common idiom that garbage collected languages usually have support for this within their standard library. For C# that's the ConditionalWeakTable. Example:

ConditionalWeakTable<IMyTerminalAction, ActionWrapper> ActionWrappers
This fixes the memory leak. The key's are stored as WeakReferences and hence don't prevent the object from being garbage collected. When they are, they're automatically removed from the table.

There's one caveat though. The table does not allow iterating of its entries. Usually that isn't necessary, but if that is, one could use a List<WeakReference> instead.

So these two classes help prevent memory leaks in mods, but unfortunately are not whitelisted in the ModAPI.

Replies (2)

photo
1

I should add that every time a block is placed it creates new Action objects. The Buildinfo mod will track these meaning they stay in memory until the game is reloaded or server is restarted. Even if the block they were created for is later removed, in which case these objects leak memory.


So this is more a bug report than a feature request. The bug being that WeakReference and ConditionalWeakTable not being whitelisted causes mods to leak memory.

photo
2

Anything that enables even better and even more mods is worth a vote!

Remember: Always consider voting, even if you don't need this, even if you don't know whether you need this. If a modder is asking for it, there's probably a good reason for it and supporting the request can only benefit you either way.

Leave a Comment
 
Attach a file