Closed gotmachine closed 1 year ago
Thanks for your insight and feedback, we'll definitely take this into account!
Just to clarify, the example implementation was not really copying the handler list because of multi-threading, it was done simply to allow a handler to unsubscribe itself (remove itself from the list of handlers) while being executed, without causing the Collection was modified; enumeration operation may not execute.
error, since the list of handlers was iterated through using a foreach. (Which, as I can see, you prevent by just using a backwards for loop.)
Check the messaging
branch
Added in #255
Following the discussion on discord the other day, I got bored this afternoon and wrote an alternative implementation for a system allowing mods to send messages to each other.
Compared to the implementation that was proposed on discord, this aim at being as straightforward to use and versatile as possible, while offering the best performance, notably by avoiding GC allocations, type checking and dictionary lookups past the initial
MessageBus
declaration and reference acquisition. The implementation allows parameterless messages, or messages with up to 4 parameters (a bit of copypasta would likely be nice to extend it to 8). This adds a bit of boilerplate code that could technically be avoided by having a single parameter version than have users define a Tuple, but Tuples have a non-negligible impact on performance compared to using parameters (Tuples are technically structs, and struct copying at scale is far from free).On a side note, it seemed the discord implementation was aiming at some thread safety capabilities by copying the delegate list. This won't work, as copying the invocation list still is unsafe from a concurrency perspective. Making such a system really thread safe would require something quite a lot more involving, and I'm not sure I see the point since nothing in KSP 2 codebase is thread safe anyway.
Example usage :
This is fully untested, but feel free to do anything with this :)